Access elements in a list
Subsetting a list is similar to subsetting a vector or data frame, with one extra useful operation.
To access the elements in the list, use [ ]
. This will always return another list.
my_list[1]
$my_words
[1] "I <3 R"
my_list[c(1,2)]
$my_words
[1] "I <3 R"
$my_numbers
[1] 42 24
To pull out the data inside each element of your list, use [[ ]]
.
my_list[[1]]
[1] "I <3 R"
If your list is named, you can use the $
operator: my_list$my_words
. This is the same as using [[ ]]
to return the inner data.
This is a part of the course
“Introduction to R for Finance”
Exercise instructions
- The
portfolio
named list is available for use. - Access the second and third elements of
portfolio
using[ ]
andc()
. - Use
$
to access thecorrelation
data.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Second and third elements of portfolio
# Use $ to get the correlation data