# Lists

| September 10th, 2013

## Lists, why would you need them?

Congratulations! At this point in the course you are already familiar with:

• Vectors (one dimensional array): can hold numeric, character or logical values. The elements in a vector all have the same data type.
• Matrices (two dimensional array): can hold numeric, character or logical values. The elements in a matrix all have the same data type.
• Data frames (two-dimensional objects): can hold numeric, character or logical values. Within a column all elements have the same data type, but different columns can be of different data type.

Pretty sweet for an R newbie, right? ;-)

### Instructions

`# no pec` `# Just click the 'Submit Answer' button.` `# Just click the 'Submit Answer' button.` ``` success_msg("Ready, set, go! Continue to the next exercise.") ```

Just click the 'Submit Answer' button.

## Lists, why would you need them? (2)

A list in R is similar to your to-do list at work or school: the different items on that list most likely differ in length, characteristic, type of activity that has to do be done, ...

A list in R allows you to gather a variety of objects under one name (that is, the name of the list) in an ordered way. These objects can be matrices, vectors, data frames, even other lists, etc. It is not even required that these objects are related to each other in any way.

You could say that a list is some kind super data type: you can store practically any piece of information in it!

### Instructions

Click 'Submit Answer' to start the first exercise on lists.

`# no pec` `# Click 'Submit Answer' to start the first exercise on lists.` `# Click 'Submit Answer' to start the first exercise on lists.` ``` success_msg("Cool. Let's get our hands dirty!") ```

Click 'Submit Answer' to start the first exercise on lists.

## Creating a list

Let us create our first list! To construct a list you use the function `list()`:

``````my_list <- list(comp1, comp2 ...)
``````

The arguments to the list function are the list components. Remember, these components can be matrices, vectors, other lists, ...

### Instructions

Construct a list, named `my_list`, that contains the variables `my_vector`, `my_matrix` and `my_df` as list components.

`# no pec` ```# Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Construct list with these different elements: my_list <- ``` ```# Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Construct list with these different elements: my_list <- list(my_vector, my_matrix, my_df)``` ``` msg = "Do not remove or change the definition of the variables `my_vector`, `my_matrix` or `my_df`!" test_object("my_vector", undefined_msg = msg, incorrect_msg = msg) test_object("my_matrix", undefined_msg = msg, incorrect_msg = msg) test_object("my_df", undefined_msg = msg, incorrect_msg = msg) test_object("my_list", incorrect_msg = "It looks like `my_list` does not contain the correct elements. Make sure to pass the variables `my_vector`, `my_matrix` and `my_df` to the `list()` function, separated by commas, in this order.") success_msg("Wonderful! Head over to the next exercise.") ```

Use the `list()` function with `my_vector`, `my_matrix` and `my_df` as arguments separated by a comma.

## Creating a named list

Well done, you're on a roll!

Just like on your to-do list, you want to avoid not knowing or remembering what the components of your list stand for. That is why you should give names to them:

``````my_list <- list(name1 = your_comp1,
name2 = your_comp2)
``````

This creates a list with components that are named `name1`, `name2`, and so on. If you want to name your lists after you've created them, you can use the `names()` function as you did with vectors. The following commands are fully equivalent to the assignment above:

``````my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")
``````

### Instructions

• Change the code of the previous exercise (see editor) by adding names to the components. Use for `my_vector` the name `vec`, for `my_matrix` the name `mat` and for `my_df` the name `df`.
• Print out `my_list` so you can inspect the output.
`# no pec` ```# Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Adapt list() call to give the components names my_list <- list(my_vector, my_matrix, my_df) # Print out my_list ``` ```# Vector with numerics from 1 up to 10 my_vector <- 1:10 # Matrix with numerics from 1 up to 9 my_matrix <- matrix(1:9, ncol = 3) # First 10 elements of the built-in data frame mtcars my_df <- mtcars[1:10,] # Adapt list() call to give the components names my_list <- list(vec = my_vector, mat = my_matrix, df = my_df) # Print out my_list my_list``` ``` msg = "Do not remove or change the definiton of the variables `my_vector`, `my_matrix` or `my_df`!" test_object("my_vector", undefined_msg = msg, incorrect_msg = msg) test_object("my_matrix", undefined_msg = msg, incorrect_msg = msg) test_object("my_df", undefined_msg = msg, incorrect_msg = msg) test_object("my_list", incorrect_msg = "It looks like `my_list` does not contain the correct elements.") test_object("my_list", eq_condition = "equal", incorrect_msg = "It looks like `my_list` does not contain the correct naming for the components. Make sure you use the names `vec`, `mat` and `df`, respectively. Check out the hint if you're struggling."); test_output_contains("my_list", incorrect_msg = "Don't forget to print `my_list` to the console! Simply add `my_list` on a new line in the editor.") success_msg("Great! Not only do you know how to construct lists now, you can also name them; a skill that will prove most useful in practice. Continue to the next exercise.") ```

The first method of assigning names to your list components is the easiest. It starts like this: ``` my_list <- list(vec = my_vector) ``` Add the other two components in a similar fashion.

## Creating a named list (2)

Being a huge movie fan (remember your job at LucasFilms), you decide to start storing information on good movies with the help of lists.

Start by creating a list for the movie "The Shining". We have already created the variables `mov`, `act` and `rev` in your R workspace. Feel free to check them out in the console.

### Instructions

Complete the code on the right to create `shining_list`; it contains three elements:

• moviename: a character string with the movie title (stored in `mov`)
• actors: a vector with the main actors' names (stored in `act`)
• reviews: a data frame that contains some reviews (stored in `rev`)

Do not forget to name the list components accordingly (names are moviename, actors and reviews).

```mov <- "The Shining" act <- c("Jack Nicholson","Shelley Duvall","Danny Lloyd","Scatman Crothers","Barry Nelson") sources <- c("IMDb1","IMDb2","IMDb3") comments <- c("Best Horror Film I Have Ever Seen","A truly brilliant and scary film from Stanley Kubrick","A masterpiece of psychological horror") scores <- c(4.5,4,5) rev <- data.frame(scores, sources, comments) rm(scores, sources, comments)``` ```# The variables mov, act and rev are available # Finish the code to build shining_list shining_list <- list(moviename = mov)``` ```# The variables mov, act and rev are available # Finish the code to build shining_list shining_list <- list(moviename = mov, actors = act, reviews = rev)``` ``` msg = "Do not remove or change the definition of the pre-set variables!" lapply(c("mov", "rev", "act"), test_object, undefined_msg = msg, incorrect_msg = msg) test_object("shining_list", incorrect_msg = "It looks like `shining_list` does not contain the correct elements: the first element should be `mov`, the second element `act`, and the third `rev`.") test_object("shining_list", eq_condition = "equal", incorrect_msg = "It looks like `shining_list` does not contain the correct naming for the components: name the first element `moviename`, the second element `actors`, and the third element `reviews`."); success_msg("Wonderful! You now know how to construct and name lists. As in the previous chapters, let's look at how to select elements for lists. Head over to the next exercise") ```

`shining_list <- list(moviename = mov)` is only part of the solution; it's your job to also add `act` and `rev` to the list, with the appropriate names.

## 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.

### 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.
`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?

## Adding more movie information to the list

Being proud of your first list, you shared it with the members of your movie hobby club. However, one of the senior members, a guy named M. McDowell, noted that you forgot to add the release year. Given your ambitions to become next year's president of the club, you decide to add this information to the list.

To conveniently add elements to lists you can use the `c()` function, that you also used to build vectors:

``````ext_list <- c(my_list , my_val)
``````

This will simply extend the original list, `my_list`, with the component `my_val`. This component gets appended to the end of the list. If you want to give the new list item a name, you just add the name as you did before:

``````ext_list <- c(my_list, my_name = my_val)
``````

### Instructions

• Complete the code below such that an item named `year` is added to the `shining_list` with the value 1980. Assign the result to `shining_list_full`.
• Finally, have a look at the structure of `shining_list_full` with the `str()` function.
`load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/shining_list.RData"))` ```# shining_list, the list containing movie name, actors and reviews, is pre-loaded in the workspace # We forgot something; add the year to shining_list shining_list_full <- # Have a look at shining_list_full ``` ```# shining_list, the list containing movie name, actors and reviews, is pre-loaded in the workspace # Use c() to add a year to shining_list shining_list_full <- c(shining_list, year = 1980) # Have a look at shining_list_full str(shining_list_full)``` ``` 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_object("shining_list_full", eq_condition = "equal", incorrect_msg = paste("Have you correctly extended `shining_list` with an element named `year`,", "whose value is 1980? You can use `c(shining_list, year = 1980)`")) test_function("str", "object", incorrect_msg = "Don't forget to display the structure of `shining_list_full` with `str()`.") success_msg("Great! This was the last exercise on R lists! You now have a solid basis in the R programming language, but there's so much more to learn. Check out all the other DataCamp courses and become a true data science expert!") ```

Have a look at the example code in the exercise assignment. Maybe this can help you start: ``` shining_list <- c(shining_list, ...) ``` You still have to add some code where the three dots are.