使用字符向量对命名数据帧的嵌套列表进行索引-R [英] Index nested lists of named data frames using character vector - R
问题描述
我有一个嵌套的命名数据框列表,如下所示:
I have a nested list of named data frames like so:
mylist2 <- list(
list(df1.a = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df2.b = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))),
list(df3.c = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df4.d = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))),
list(df5.e = data.frame(replicate(2,sample(0:1,5,rep=TRUE))), df6.f = data.frame(replicate(2,sample(0:1,5,rep=TRUE)))))
我运行了一个测试(哪种测试并不重要),它会生成一个字符向量,告诉我此列表中的哪些数据帧很重要:
I run a test (not important what sort of test) and it produces a character vector telling me which data frames in this list are important:
test
[1] "df1.a" "df5.e"
使用此字符向量从嵌套列表中提取这些数据帧的最有效方法是什么?该测试仅显示第二个列表的名称,因此nestedlist[test]
不起作用.
What is the most efficient way to extract these data frames from the nested list using this character vector? The test only shows the names of second list, so nestedlist[test]
does not work.
推荐答案
由于OP提到它是嵌套的list
,因此我们可以遍历初始的list
,然后使用以下命令提取第二个list
的元素[
As the OP mentioned it was a nested list
, we can loop through the initial list
and then extract the elements of the second list
with [
lapply(mylist2, '[', test)
或使用tidyverse
library(tidyverse)
map(mylist2, ~ .x %>%
select(test))
更新
基于更新后的数据集:
Update
Based on the updated dataset:
Filter(length, lapply(mylist2, function(x) x[intersect(test, names(x))]))
这篇关于使用字符向量对命名数据帧的嵌套列表进行索引-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!