MulaiMulai sekarang secara gratis

Vector subsetting

Sometimes, you will only want to use specific pieces of your vectors, and you'll need some way to access just those parts. For example, what if you only wanted the first month of returns from the vector of 12 months of returns? To solve this, you can subset the vector using [ ].

Here is the 12 month return vector:

ret <- c(5, 2, 3, 7, 8, 3, 5, 9, 1, 4, 6, 3)

Select the first month: ret[1].

Select the first month by name: ret["Jan"].

Select the first three months: ret[1:3] or ret[c(1, 2, 3)].

Latihan ini adalah bagian dari kursus

Introduction to R for Finance

Lihat Kursus

Petunjuk latihan

  • The named vector ret is defined in your workspace.
  • Subset the first 6 months of returns.
  • Subset only March and May's returns using c() and "Mar", "May".
  • Run the last line of code to perform a subset that omits the first month of returns.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# First 6 months of returns


# Just March and May


# Omit the first month of returns
ret[-1]
Edit dan Jalankan Kode