Reputation: 1491
I have a nested liste, resulted from a function. Where the top element names are reapeated in the element names further down.
$`1`
$`1`$`1`
[1] 0 0 0 0 0 0 0 1 0
$`1`$`2`
[1] 0 0 0 0 0 0 0 0 0
$`2`
$`2`$`1`
[1] 0 0 0 1 1 0 0 0 0
$`2`$`2`
[1] 0 1 0 0 0 1 0 0 0
Is there a way to use an apply function (or whatever) to extract those vectors where the element and subelement names match. E.g. $1
$1
and $2
$2
. I have a huge list (4000 elements with 4000 subelements) so efficiency is thus a must.
Alternatively - I have figured out a way out of this mess by using ´melt()´, but it's too consuming for the size of my set. But if anyone know how to replicate the effect - giving a dataframe with 3 columns one for elementname, one for subelement name and one for the vector - that will also work.
Regards and thanks :)
Upvotes: 3
Views: 3817
Reputation: 66844
You can unlist
them without recursion to remove the top level list structure, and then use regex-assisted subsetting on the names of this result.
l <- list(`1`=list(`1`=rpois(6,1),`2`=rep(0,6)),`2`=list(`1`=rep(0,6),`2`=rpois(6,1)))
l2 <- unlist(l,recursive=F)
l2[grepl("([0-9]+)[.]\\1",names(l2))]
$`1.1`
[1] 2 0 2 4 1 0
$`2.2`
[1] 0 0 0 2 1 0
Upvotes: 2
Reputation: 81693
This is a way to get a list of the vectors you want:
lapply(names(dat), function(x) dat[[x]][[x]])
In a data frame:
do.call("rbind",
lapply(names(dat),
function(x) data.frame(element = x,
subelement = x,
values = dat[[x]][[x]])
)
)
Upvotes: 4