#--------------------------------------- # # A list is the most general sort of structure in R. A # list can have elements of different types and different # lengths. Its elements can be named (more common) or not # (less common). Here's one without names. # list (1:3, c("Yes", "No"), c(T, F, F, T), log) # # Notice the double-square brackets. Here's one with names. (mylist <- list (Red = 1:3, Blue = letters[5:9], Black = c(F, F, T))) # # We get at the elements of a named list with dollar-sign # notation. We can also use square brackets (to get a sub-list) # or double-square brackets (to get the contents) # length (mylist); lengths (mylist) mylist$Red + 1 # We can do math on a numeric vector mylist$R + 1 # We only need to uniquely identify the name mylist$Bl + 1 # Ambiguous mylist["Red"] # Returns a list with one item (full name needed) mylist["Red"] + 1 # We can't do math on a list mylist[["Red"]] # Returns the element itself (full name needed) mylist[[1]] + 1 # same thing mylist[c(2, 1)] # Usual extraction for a sublist # # Handy utility functions include length (# of items in list), # lengths (sizes of each item), unlist length (mylist) lengths (mylist) unlist (mylist) # make list into vector class (mylist); is.list (mylist) # # # Add a new item mylist$White <- c(1, 1, 2, 3, 5, 8, 13) mylist # # Remove an item by assigning NULL to it. In this case # you will need the full name # mylist$Blue <- NULL mylist # # # # lapply() operates on each element of a list, returning a # list; sapply() does the same but tries to return a vector # mylist2 <- list (A = 1:10, B = 65:80, C = 220:250) lengths (mylist2) sapply (mylist2, class) # what class is each element # Suppose we have some NAs in there. This comes up often. mylist2$A[c(4, 6)] <- NA; mylist2$C[22:25] <- NA sapply (mylist2, function (x) sum (is.na (x))) # vector lapply (mylist2, function (x) sum (is.na (x))) # list # # sapply() will return a list if it has to # sapply (mylist2, function (x) which (x > 247))