Home > Enterprise >  Get the column of a list of lists in R
Get the column of a list of lists in R

Time:12-31

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?

CodePudding user response:

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

3) If we know that L is regularly shaped we could convert it to a matrix and then take the second column.

matrix(unlist(L), length(L), byrow = TRUE)[, 2]
## [1] 0.8166747 0.5753511 0.4698621

Note

# input in reproducible form
L <- list(
  list(0.8198689, 0.8166747),
  list(0.5798426, 0.5753511),
  list(0.4713508, 0.4698621))

CodePudding user response:

Can you explain how sapply do the job ?

I assume that sapply will apply a function on the list L but what is exactly the function here ? As far as I know, '[[' is not a function

CodePudding user response:

The simple way to do this using purrr is just to use map(), which returns a list.

library(purrr)

map(L, 2)

If you want a (numeric) vector, use map_dbl().

map_dbl(L, 2)
# [1] 0.8166747 0.5753511 0.4698621
  • Related