简体   繁体   English

从另一个列表中的每个列表中提取相同的项目

[英]Extract the same item from each list within a list within another list

I have a list (modified from this example subsetting lists ) that looks like 我有一个列表(从此示例子集列表修改而来)看起来像

l3 <- list(item1 = list(item1a = data.frame(matrix(1:9,ncol = 3)),
                        item1b=letters[1:5], 
                        item1c = c(T, F, T, T)), 
           item2 = list(item2a = data.frame(matrix(10:19,ncol = 3)),
                        item2b=letters[1:5], 
                        item2c = c(T, F, T, T)))



l3
$item1
    $item1$item1a
      X1 X2 X3
    1  1  4  7
    2  2  5  8
    3  3  6  9

$item1$item1b
[1] "a" "b" "c" "d" "e"

$item1$item1c
[1]  TRUE FALSE  TRUE  TRUE


$item2
$item2$item2a
  X1 X2 X3
1 10 14 18
2 11 15 19
3 12 16 10
4 13 17 11

$item2$item2b
[1] "a" "b" "c" "d" "e"

$item2$item2c
[1]  TRUE FALSE  TRUE  TRUE

I would like to select the X1 variable from each of the smallest list. 我想从每个最小的列表中选择X1变量。 These are the code I have written but I have not yet been successful. 这些是我编写的代码,但尚未成功。

 l3[[1:2]]["X1"]
[1] NA

This code below give the X1 for the first nested dataframe only (which is what I am looking to get for all the dataframes) 下面的代码仅为第一个嵌套数据框提供X1(这是我希望为所有数据框获取的内容)

l3[[1]]$item1a$X1 
[1] 1 2 3

Any help is very much appreciated! 很感谢任何形式的帮助!

May be this helps 也许这会有所帮助

library(purrr)
map(l3, ~ .x[[1]]$X1)

Or using pluck with select 或者用pluckselect

library(dplyr)
map(l3, ~ .x %>% 
            pluck(1) %>% 
            select(X1))

Or if we are not a chain enthusiast, then this can be done more compactly as @ArtemSokolov mentioned 或者,如果我们不是链条爱好者,那么可以像@ArtemSokolov所说的那样更紧凑地完成此操作。

map(l3, pluck, 1, "X1")

Or with lapply 或与lapply

lapply(l3, function(x) x[[1]]$X1)

With plyr : plyr

plyr::llply(l3,function(x)x[[1]]["X1"])
$item1
  X1
1  1
2  2
3  3

$item2
  X1
1 10
2 11
3 12
4 13

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

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