简体   繁体   English

在R中子集嵌套列表

[英]Subsetting nested lists within R

I am trying to create a dataframe from nested lists from within R. Here is an example: 我试图从R内的嵌套列表创建一个数据帧。这是一个例子:

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; 我想知道如何从嵌套列表中提取所有特征'x'和特征'y',并将'y'拆分为两列; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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