Get Started

Selecting elements from a list

Your list will often be built out of numerous elements and components. Therefore, getting a single element, multiple elements, or a component out of it is not always straightforward.

One way to select a component is using the numbered position of that component. For example, to "grab" the first component of shining_list you type

shining_list[[1]]

A quick way to check this out is typing it in the console. Important to remember: to select elements from vectors, you use single square brackets: [ ]. Don't mix them up!

You can also refer to the names of the components, with [[ ]] or with the $ sign. Both will select the data frame representing the reviews:

shining_list[["reviews"]]
shining_list$reviews

Besides selecting components, you often need to select specific elements out of these components. For example, with shining_list[[2]][1] you select from the second component, actors (shining_list[[2]]), the first element ([1]). When you type this in the console, you will see the answer is Jack Nicholson.

This is a part of the course

“Introduction to R”

View Course

Exercise instructions

  • Select from shining_list the vector representing the actors. Simply print out this vector.
  • Select from shining_list the second element in the vector representing the actors. Do a printout like before.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# shining_list is already pre-loaded in the workspace

# Print out the vector representing the actors


# Print the second element of the vector representing the actors

This exercise is part of the course

Introduction to R

BeginnerSkill Level
4.7+
595 reviews

Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.

As opposed to vectors, lists can hold components of different types, just as your to-do lists can contain different categories of tasks. This chapter will teach you how to create, name, and subset these lists.

Exercise 1: Lists, why would you need them?Exercise 2: Lists, why would you need them? (2)Exercise 3: Creating a listExercise 4: Creating a named listExercise 5: Creating a named list (2)Exercise 6: Selecting elements from a list
Exercise 7: Creating a new list for another movie

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