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)]
.
This exercise is part of the course
Introduction to R for Finance
Exercise instructions
- 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.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# First 6 months of returns
# Just March and May
# Omit the first month of returns
ret[-1]