You can extract components from lists in R. Consider two lists. The display of both the unnamed list baskets.list and the named list baskets.nlist show already that the way to access components in a list is a little different.

That’s not completely true, though. In the case of a named list, you can access the components using the $, as you do with data frames. For both named and unnamed lists, you can use two other methods to access components in a list:

  • Using [[ ]] gives you the component itself.

  • Using [ ] gives you a list with the selected components.

Using [[ ]]

If you need only a single component and you want the component itself, you can use [[ ]], like this:

> baskets.list[[1]]
     1st 2nd 3rd 4th 5th 6th
Granny   12  4  5  6  9  3
Geraldine  5  4  2  4 12  9

If you have a named list, you also can use the name of the component as an index, like this:

> baskets.nlist[["scores"]]
     1st 2nd 3rd 4th 5th 6th
Granny   12  4  5  6  9  3
Geraldine  5  4  2  4 12  9

In each case, you get the component itself returned. Both methods give you the original matrix baskets.team.

You can’t use logical vectors or negative numbers as indices when using [[ ]]. You can use only a single value — either a (positive) number or a component name.

Using [ ]

You can use [ ] to extract either a single component or multiple components from a list, but in this case the outcome is always a list. [ ] is more flexible than [[ ]], because you can use all the tricks you also use with vector and matrix indices. [ ] can work with logical vectors and negative indices as well.

So, if you want all components of the list baskets.list except for the first one, you can use the following code:

> baskets.list[-1]
[[1]]
[1] "season 2010-2011"

Or if you want all components of baskets.nlist where the name contains season, you can use the following code:

> baskets.nlist[grepl("season", names(baskets.nlist))]
$season
[1] "2010-2011"

Note that, in both cases, the returned value is a list, even if it contains only one component. R simplifies arrays by default, but the same doesn’t count for lists.

About This Article

This article is from the book:

About the book authors:

Andrie de Vries is a leading R expert and Business Services Director for Revolution Analytics. With over 20 years of experience, he provides consulting and training services in the use of R. Joris Meys is a statistician, R programmer and R lecturer with the faculty of Bio-Engineering at the University of Ghent.

This article can be found in the category: