A list is an R structure that allows you to combine elements of different types, including lists. This tutorial covers the basics of managing lists.

Creating

To create a list we can use the list() function:

To add additional list components to a list we can leverage the list() and append() functions:

To add individual elements to a specific list component we need to introduce some subsetting which is further discussed the Subsetting section below.

The attributes that you can add to lists include names, general comments, and specific list item comments:

Subsetting

To subset lists we can utilize the single bracket[ ], double brackets [[ ]], and dollar sign $. “If list x is a train carrying objects, then x[[5]] is the object in car 5; x[4:6] is a train of cars 4-6” - @RLangTip Subset List - Preserving Output as a List To extract one or more list items while preserving1 the output in list format use the [ ] operator: Subset List - Simplify Output To extract one or more list items and simplifying1 the output use the [ ] or $ operator:

One thing that differentiates the [[ operator from the $is that the [[ operator can be used with computed indices. The$ operator can only be used with literal names.

Subset List - Get Elements Out of a List

To extract individual elements out of a specific list item combine the [[ (or \$) operator with the [ operator:

Subset List - Dealing with Nested Lists

If you have nested lists you can expand the ideas above to extract items and elements:

Go to top

1. Its also important to understand the difference between simplifying and preserving subsetting. Simplifying subsets returns the simplest possible data structure that can represent the output. Preserving subsets keeps the structure of the output the same as the input. See Hadley Wickham's section on Simplifying vs. Preserving Subsetting to learn more."↩" </P>