What are the differences between vector and list data types in R?

DCR picture DCR · Dec 21, 2011 · Viewed 96k times · Source

What are the main differences between vector and list data types in R? What are the advantages or disadvantages of using (or not) these two data types?

I would appreciate seeing examples that demonstrate the use cases of the data types.

Answer

IRTFM picture IRTFM · Dec 21, 2011

Technically lists are vectors, although very few would use that term. "list" is one of several modes, with others being "logical", "character", "numeric", "integer". What you are calling vectors are "atomic vectors" in strict R parlance:

 aaa <- vector("list", 3)
 is.list(aaa)   #TRUE
 is.vector(aaa)  #TRUE

Lists are a "recursive" type (of vector) whereas atomic vectors are not:

is.recursive(aaa)  # TRUE
is.atomic(aaa)  # FALSE

You process data objects with different functions depending on whether they are recursive, atomic or have dimensional attributes (matrices and arrays). However, I'm not sure that a discussion of the "advantages and disadvantages" of different data structures is a sufficiently focused question for SO. To add to what Tommy said, besides lists being capable of holding an arbitrary number of other vectors there is the availability of dataframes which are a particular type of list that has a dimensional attribute which defines its structure. Unlike matrices and arrays which are really folded atomic objects, dataframes can hold varying types including factor types.

There's also the caveat that the is.vector function will return FALSE when there are attributes other than names. See: what is vector?