Reputation: 33
I am trying to create a dataframe from nested lists from within R. Here is an example:
mylist<-list(file1 = list("a", sample1 = list(x = 2, y = list(c(1, 2)),
sample2 = list(x = 4, y = list(c(3, 8))))), file2 = list(
"a", sample1 = list(x = 6, y = list(c(6, 4)), sample2 = list(
x = 6, y = list(c(7, 4))))))
I would like to know how I could extract all the features 'x' and the features 'y' from the nested lists, with 'y' split into two columns; one for each value?
Thanks you for your time everyone!
Upvotes: 3
Views: 276
Reputation: 50718
I'm not exactly sure what you're expected output is supposed to be like, but perhaps something like this?
library(tidyverse)
unlist(mylist) %>%
data.frame(val = .) %>%
rownames_to_column("id") %>%
filter(str_detect(id, "(x|y1|y2)")) %>%
separate(id, into = c("id", "col"), sep = "\\.(?=\\w+$)") %>%
spread(col, val)
# id x y1 y2
#1 file1.sample1 2 1 2
#2 file1.sample1.sample2 4 3 8
#3 file2.sample1 6 6 4
#4 file2.sample1.sample2 6 7 4
Upvotes: 1