Using R, my data set L is a list of lists. My print(L) produces the following output:
[[1]]
[[1]][[1]]
[1] 0.8198689
[[1]][[2]]
[1] 0.8166747
[[2]]
[[2]][[1]]
[1] 0.5798426
[[2]][[2]]
[1] 0.5753511
[[3]]
[[3]][[1]]
[1] 0.4713508
[[3]][[2]]
[1] 0.4698621
And I want to get a vector of the second column. However unlist(L[[2]]) gives me the second row (not the second column) and L[,2] gives me the error Error in L[, 2] : incorrect number of dimensions. I tried also L$'2‘ and didn’t work.
How can I get the vector of the second column of this data set in R?
>Solution :
1) Assuming the input shown reproducibly in the Note at the end use sapply (or use lapply if you want it as a list). No packages are used.
sapply(L, `[[`, 2)
## [1] 0.8166747 0.5753511 0.4698621
2) Using purrr we have:
library(purrr)
transpose(L)[[2]]
## [[1]]
## [1] 0.8166747
##
## [[2]]
## [1] 0.5753511
##
## [[3]]
## [1] 0.4698621
Note
# input in reproducible form
L <- list(
list(0.8198689, 0.8166747),
list(0.5798426, 0.5753511),
list(0.4713508, 0.4698621))