简体   繁体   中英

Subsetting nested lists within R

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM