Reputation: 7517
I have a list of list of data.frames called G
.
In BASE R, I was wondering how I could separately extract elements dint
and SD
in A
and B
skipping any NULL
elements?
My desired output is: dint = list(A = 1:3, B = c(1:4, 5:6) )
SD = list(A = 0:2, B = c(2:5, 3:4) )
Here is the data:
G <- list(A = list(short = NULL, short2 = NULL, del1 = data.frame(dint = 1:3, SD = 0:2),
del11 = NULL),
B = list(short = data.frame(dint = 1:4, SD = 2:5), short2 = NULL, del1 =
data.frame(dint = 5:6, SD = 3:4), del11 = NULL))
Upvotes: 1
Views: 129
Reputation: 886948
We can just call a single lapply
and extract the components
lapply(G, function(x) do.call(rbind, x)$dint)
#$A
#[1] 1 2 3
#$B
#[1] 1 2 3 4 5 6
Or to extract the 'SD'
lapply(G, function(x) do.call(rbind, x)$SD)
#$A
#[1] 0 1 2
#$B
#[1] 2 3 4 5 3 4
It can be made into a function
f1 <- function(lstI, elementName){
lapply(lstI, function(x) do.call(rbind, x)[[elementName]])
}
f1(G, "dint")
f1(G, "SD")
rbind
will get both the columns
lapply(G, function(x) do.call(rbind, x))
Upvotes: 1
Reputation: 388817
We could use nested lapply
lapply(G, function(x) unlist(lapply(x, `[[`, 'dint'), use.names = FALSE))
#$A
#[1] 1 2 3
#$B
#[1] 1 2 3 4 5 6
and similar for "SD"
as well
lapply(G, function(x) unlist(lapply(x, `[[`, 'SD'), use.names = FALSE))
#$A
#[1] 0 1 2
#$B
#[1] 2 3 4 5 3 4
Upvotes: 1