Get startedGet started for free

What is a list?

1. What is a list?

Imagine you are going to the grocery store. To keep organized, and to remember what to buy, you have probably brought along a grocery list. Think about what might be on that. Cereal, paper towels, pizza, all kinds of different things with different shapes and structures. No matter what it might be, if you can find it in a grocery store, you might put it on your list. Just like your grocery list, in R, there is a kind of super data structure, also called a List, that allows you to group together other data structures into, well, a list.

2. Lists

Imagine if you wanted to put the cash data frame that you worked with in chapter 3, and a character vector containing the name of your company together somehow. There is no pretty way to just add a new column for the company name, it is only of length 1, while your data frame has more rows than that. Yet, you still want to hold them together somehow. Let's consider what would happen if you put these into a list named my_company.

3. Lists

Creating a list is simple. Just use the list function, and pass in all of the data structures that you want inside your list. Here, we are passing in the company_name variable, and the cash data frame. When we print our list, we see a tidy data structure showing both objects.

4. Subsetting lists

Accessing elements inside of a list is slightly more complicated than if you just had a data frame or some other structure, because there are now two levels that you have to deal with. To subset the outer level, the list itself, you use the normal brackets. This will always return another list. Here, you can see we have retrieved the first element of the list, which is another list that contains the company name. To gain access to the company name data itself, we would have to use double brackets. Notice the difference between the first and second example. The single bracket returns a subsetted list, the double brackets returns the data inside the list. We can also get access to the entire data frame using double brackets. Later, you will learn about a shortcut that you can use to access elements of named lists.

5. Let's practice!

In the next few exercises, you will create a list corresponding to your portfolio of stocks. Then, you will name the items in your list and learn how to add and remove elements from it. Happy coding!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.