mylist <- list (a = 1:5, b = "Hi There", c = function(x) x * sin(x))Now the list "mylist" contains three things, named "a," "b," and "c." Their lengths are different: a has length 5, b has length 1, and c is a function, so it doesn't really have a length. (Technically, it has length 1, just because somebody decided that the "length" of a function should be one.) To extract an item from a list, you can use the single brackets, but that will give you back a list. Thus
mylist $a:  1 2 3 4 5 > mylist + 1 # Can we do math on that? Error in mylist + 1: Non-numeric first operand DumpedWe can't do math on a list. Generally you will want single brackets when you're extracting pieces of a list to make into another list.
If we want one of the items in its original form, we can extract it with double square brackets, or by using the dollar sign and the name. (The items in the list don't need to have names, but in this case they do have names, since we supplied them at the time we created the list.)
mylist[]  1 2 3 4 5 > mylist$a  1 2 3 4 5 > mylist$a + 1 # Can we do math on that?  2 3 4 5 6 # Answer: yes. > mylist$a # What's the second element of the item named "a"?  2 # Answer: 2. > mylist$a[-2] # Give me everything from "a" except the second element  1 3 4 5 # Remember the negative subscript?Usually a list will consist of vectors. As always, every element of a vector must be of the same type (numeric, character, logical, complex...). A list is a natural way, then, to store items of different types and lengths. For example, when you fit a statistical model you might get back a vector of (numeric) coefficients, a logical vector saying which terms were included in the model, a matrix of data, a vector of messages from the fitting routines, a so on. A list is the natural way to represent this sort of thing in R.
> mylist # Here's what mylist looks like right now $a:  1 2 3 4 5 $b:  "Hi There" $c: function(x) x * sin(x) > mylist$d <- "New item" # Add a new item and print out the list > mylist # We could have assigned to mylist[]; then that $a: # new element would not have had a name  1 2 3 4 5 $b:  "Hi There" $c: function(x) x * sin(x) $d:  "New item" > length(mylist) # The length of a list is the number of elements  4 # (So for a data frame, the length is # the number of columns) > mylist$b <- NULL # Delete item b and print out the list > mylist $a:  1 2 3 4 5 $c: function(x) x * sin(x) $d:  "New item"
Return to R docs