Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the column of a list of lists in R

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading