【问题标题】:Extract object from a list based on element name in R根据R中的元素名称从列表中提取对象
【发布时间】:2020-04-29 07:45:29
【问题描述】:

我有一个包含 94 个矩阵的列表,这里显示了其中的一个子集:

 > summary(full_matrix)

            Length Class  Mode   
 Alex_1         64 -none- numeric
 Alex_10      2500 -none- numeric
 Alex_11      2916 -none- numeric
 Alex_12     20736 -none- numeric
 Lily_1        441 -none- numeric
 Lily_10     57600 -none- numeric
 Lily_11     94249 -none- numeric
 Lily_12    167281 -none- numeric
 Lily_13    206116 -none- numeric
 Naima_1       169 -none- numeric
 Naima_10   209764 -none- numeric
 Naima_11   262144 -none- numeric
 Naima_12   209764 -none- numeric
 Naima_13   177241 -none- numeric
 Naima_14   143641 -none- numeric

我在每个矩阵上运行了一些代码,我可以使用lapply() 成功完成这些代码。但是,代码运行非常缓慢,并且需要数小时才能在完整列表上运行。所以我想按元素名称拆分列表。我已经使用subset_matrix <- full_matrix[1:4] 手动成功地完成了这项工作,在本例中将给出:

 > summary(subset_matrix)
         Length Class  Mode   
 Alex_1     64  -none- numeric
 Alex_10  2500  -none- numeric
 Alex_11  2916  -none- numeric
 Alex_12 20736  -none- numeric

但是,如果我对脚本的前面部分进行任何更改,这很笨拙并且会变得混乱。我想做的是选择所有包含“Alex_”、“Lily_”、“Naima_”等的元素,并创建这些元素的子列表。我认为this solution 可能有用,但它给了我一个空列表:

 > matrix_alex <- full_matrix[c("Alex_")] # subset for individual infants
 > summary(matrix_alex)
      Length Class  Mode
  <NA> 0      -none- NULL

【问题讨论】:

    标签: r list


    【解决方案1】:

    "Alex_" 不在您的列表中。

    names(full_list)
    # [1] "Alex_01"  "Alex_02"  "Alex_03"  "Bella_01" "Bella_02" "Bella_03"
    

    您可能想要使用 grep 来查找模式。

    subset_list <- full_list[grep("Alex_", names(full_list))]
    # $Alex_01
    # [,1]
    # [1,]   NA
    # 
    # $Alex_02
    # [,1]
    # [1,]   NA
    # 
    # $Alex_03
    # [,1]
    # [1,]   NA
    

    数据:

    full_list <- list(Alex_01=matrix(),
                      Alex_02=matrix(),
                      Alex_03=matrix(),
                      Bella_01=matrix(),
                      Bella_02=matrix(),
                      Bella_03=matrix())
    

    【讨论】:

    • 完美!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多