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 !
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With