Get Started

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”

View Course

Exercise instructions

  • The portfolio named list is available for use.
  • Access the second and third elements of portfolio using [ ] and c().
  • Use $ to access the correlation 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

This exercise is part of the course

Introduction to R for Finance

BeginnerSkill Level
4.8+
12 reviews

Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.

Wouldn't it be nice if there was a way to hold related vectors, matrices, or data frames together in R? In this final chapter, you will explore lists and many of their interesting features by building a small portfolio of stocks.

Exercise 1: What is a list?Exercise 2: Create a listExercise 3: Named listsExercise 4: Access elements in a list
Exercise 5: Adding to a listExercise 6: Removing from a listExercise 7: A few list creating functionsExercise 8: Split itExercise 9: Split-Apply-CombineExercise 10: AttributesExercise 11: Congratulations!

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free