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)]
.
Este exercício faz parte do curso
Introduction to R for Finance
Instruções do exercício
- 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# First 6 months of returns
# Just March and May
# Omit the first month of returns
ret[-1]