Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elements from list of list in R

Tags:

list

r

lapply

I have a list of list as follow :

l = list(list(v = numeric(0), pos = 10), list(v = numeric(0), pos = 10), 
    list(v = numeric(0), pos = 10), list(v = 1.227, pos = 19), 
    list(v = 1.227, pos = 19), list(v = 15.2, pos = 19))

I would like to extract element v from each list. I have checked this slution, but it does not work for me. The first method using rapply and unique function will include the pos values as well and also I would like to keep all v values even if they are repeated or they are zero or numeric(0) ! The second method with :

matrix(unlist(l),ncol=2,byrow=TRUE)

Is also not working because I have some numeric(0) in my lists for the value v !

like image 404
user9112767 Avatar asked Jan 25 '26 12:01

user9112767


2 Answers

You can try:

sapply(l, `[`, "v")

$v
numeric(0)

$v
numeric(0)

$v
numeric(0)

$v
[1] 1.227

$v
[1] 1.227

$v
[1] 15.2

Or if you mean a vector containing values from each list:

vec <- sapply(l, `[`, "v")
vec[lengths(vec) == 0] <- NA
unlist(vec)

     v      v      v      v      v      v 
    NA     NA     NA  1.227  1.227 15.200
like image 178
tmfmnk Avatar answered Jan 27 '26 02:01

tmfmnk


Another option is to use the purrr::map() variants which have an argument for handling NULL or zero length entries.

library(purrr)

map_dbl(l, "v", .default = NA)
[1]     NA     NA     NA  1.227  1.227 15.200
like image 30
Ritchie Sacramento Avatar answered Jan 27 '26 01:01

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!