Many people who start with R get confused by lists in the beginning. There’s really no need for that — a list has only two important parts: the components and the names. And in the case of unnamed lists, you don’t even have to worry about the latter. But if you look at the structure of baskets.list in the following output, you can see why people often shy away from lists.

> str(baskets.list)
List of 2
 $ : num [1:2, 1:6] 12 5 4 4 5 2 6 4 9 12 ...
 ..- attr(*, "dimnames")=List of 2
 .. ..$ : chr [1:2] "Granny" "Geraldine"
 .. ..$ : chr [1:6] "1st" "2nd" "3rd" "4th" ...
 $ : chr "2010-2011"

This really looks like some obscure code used by the secret intelligence services during World War II. Still, when you know how to read it, it’s pretty easy to read. So let’s split up the output to see what’s going on here:

  • The first line simply tells you that baskets.list is a list with two components.

  • The second line contains a $, which indicates the start of the first component. The rest of that line you should be able to read now: It tells you that this first component is a numeric matrix with two rows and six columns.

  • The third line is preceded by .., indicating that this line also belongs to the first component. If you look at the output of str( you see this line and the following two as well. R keeps the row and column names of a matrix in an attribute called dimnames. For now, you have to remember only that an attribute is an extra bit of information that can be attached to almost any object in R.

  • The dimnames attribute is by itself again a list.

  • The fourth and fifth lines tell you that this list contains two components: a character vector of length 2 and one of length 6. R uses the .. only as a placeholder, so you can read from the indentation which lines belong to which component.

  • Finally, the sixth line starts again with a $ and gives you the structure of the second component — in this case, a character vector with only one value.

If you look at the output of the str(baskets.nlist), you get essentially the same thing. The only difference is that R now puts the name of each component right after the $.

In many cases, looking at the structure of the output from a function can give you a lot of insight into which information is contained in that object. Often, these objects are lists, and the piece of information you’re looking for is buried somewhere in that list.

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: