Assuming you have something like the following:
myList <- list(`0` = c(`1` = 10, `2` = 20, `3` = 30, `4` = 72),
`1` = c(`1` = 15, `2` = 9, `3` = 7))
myList
# $`0`
# 1 2 3 4
# 10 20 30 72
#
# $`1`
# 1 2 3
# 15 9 7
Use sapply()
or lapply()
to get into your list and extract whatever columns you want. Some examples.
# As a list of one-column data.frames
lapply(myList, `[`, 1)
# $`0`
# 1
# 10
#
# $`1`
# 1
# 15
# As a list of vectors
lapply(myList, `[[`, 1)
# $`0`
# [1] 10
#
# $`1`
# [1] 15
# As a named vector
sapply(myList, `[[`, 1)
# 0 1
# 10 15
# As an unnamed vector
unname(sapply(myList, `[[`, 1))
# [1] 10 15
Other variants of the syntax that also get you there include:
## Same output as above, different syntax
lapply(myList, function(x) x[1])
lapply(myList, function(x) x[[1]])
sapply(myList, function(x) x[[1]])
unname(sapply(myList, function(x) x[[1]]))
A Nested List Example
If you do have nested lists (lists within lists), try the following variants.
# An example nested list
myNestedList <- list(A = list(`0` = c(`1` = 10, `2` = 20, `3` = 30, `4` = 72),
`1` = c(`1` = 15, `2` = 9, `3` = 7)),
B = list(`0` = c(A = 11, B = 12, C = 13),
`1` = c(X = 14, Y = 15, Z = 16)))
# Run the following and see what you come up with....
lapply(unlist(myNestedList, recursive = FALSE), `[`, 1)
lapply(unlist(myNestedList, recursive = FALSE), `[[`, 1)
sapply(unlist(myNestedList, recursive = FALSE), `[[`, 1)
rapply(myNestedList, f=`[[`, ...=1, how="unlist")
Note that for lapply()
and sapply()
you need to use unlist(..., recursive = FALSE)
while for rapply()
(recursive apply), you refer to the list directly.