从嵌套列表中提取多列(使用对象前缀)

Extract multiple columns from nested lists (using object prefix)

我在一个公共列表中有多个嵌套列表。 我想在一个唯一的 df 中提取并存储特定对象(所有以 t.outb.out).

开头的列表

下面的 ReprEx:

mylist<-list(par1 = rnorm(1,0,1)
         , par2 = rnorm(1,0,1)
         , par3 = rnorm(1,0,1)
         , par4 = rnorm(1,0,1)
         , t.out1 = list(val1 = rnorm(1,2,1)
                         , col1 = as.data.frame(rnorm(10,0,1)))
         , t.out2 = list(val2 = rnorm(1,2,1)
                         , col2 = as.data.frame(rnorm(10,0,1)))
         , b.out3 = list(val3 = rnorm(1,2,1)
                         , col3 = as.data.frame(rnorm(10,0,1)))
         , g.out4 = list(val4 = rnorm(1,2,1)
                         , col4 = as.data.frame(rnorm(10,0,1))))

我知道如何使用(示例)mylist[["t.out1"]][[2]] 一个一个地提取我需要的元素,但我需要一些允许我对许多嵌套列表执行此操作的脚本。

我尝试了以下方法,但它不起作用

select_lists <- names(mylist)[grep("^t.*$|^b.*$", names(mylist))]
mylist[[select_lists]][[2]]

Error in mylist[[select_lists]] : no such index at level 2

预期结果应如下所示

bind_cols(mylist[["t.out1"]][[2]]
          , mylist[["t.out2"]][[2]]
          , mylist[["b.out3"]][[2]])

你可以试试:

sapply(mylist[grep("^(t|b)\.out", names(mylist))],
 function(x) unlist(x[startsWith(names(x), "col")], use.names = FALSE))
#          t.out1     t.out2      b.out3
# [1,] -0.6741380  0.4457036  0.09194051
# [2,]  0.8463555 -1.0284650  0.23858507
# [3,] -1.9122132  0.9740014 -0.16088752
# [4,] -1.4880384 -0.2844162  2.32278847
# [5,]  0.6463312 -0.4652480 -1.04187252
# [6,] -1.2264961  0.7801192 -0.83594572
# [7,]  0.4658511 -0.7364893 -0.75425093
# [8,]  1.7240282 -1.4285961  1.97459931
# [9,]  0.6239692 -0.6896502 -1.64462726
#[10,] -1.0699496  0.3033302  0.34368145

mylist[grep("^(t|b)\.out", names(mylist))] I select 以 t.outb.out[=20= 开头的那些].使用 startsWith(names(x), "col") 我得到那些盯着 col.

的人