Reputation: 2236
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
!
Upvotes: 3
Views: 721
Reputation: 40171
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
Upvotes: 5
Reputation: 34761
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
Upvotes: 3
Reputation: 73802
You could program a small extractR
.
extractR <- function(l, v) {
r <- sapply(l, `[`, "v")
sapply(r, function(i) ifelse(length(i) == 0, NA, i))
}
extractR(l, "v")
# v v v v v v
# NA NA NA 1.227 1.227 15.200
Upvotes: 1