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.

Instruction

load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/shining_list.RData")) # 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 # shining_list is already pre-loaded in the workspace # Print out the vector representing the actors shining_list$actors # Print the second element of the vector representing the actors shining_list$actors[2] msg <- "Do not remove or change the definition of `shining_list`, which is pre-loaded in the workspace!" test_object("shining_list", undefined_msg = msg, incorrect_msg = msg) test_output_contains("shining_list$actors", incorrect_msg = "Have you correctly selected and printed out the vector representing actors? You can use `shining_list$actors`, for example.") test_output_contains("shining_list$actors[2]", incorrect_msg = "To select the second actor from the vector representing actors, you should chain your selections: `shining_list$actors` represents the actors, so you can add a `[2]` to select the second element.") success_msg("Great! Selecting elements from lists is rather easy isn't it? Continue to the next exercise.")
  • To select the vector representing the actors, you can use $actors.
  • To select the third element in the vector representing the actors, you use shining_list$actors[3]. What needs to change to select the second element?

Previous: 6-5 | Creating a named list (2)

Next: 6-7 | Adding more movie information to the list

Back to Main