You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于字符串模式从命名列表中提取指定元素(R语言)

在R中提取名称含'abc'的列表元素

直接用stringr::str_detect配合列表名称筛选就能搞定,步骤如下:

  • 先确保你装了stringr包,没装的话先运行:

    install.packages("stringr")
    library(stringr)
    
  • 构造示例列表(模拟你的lst):

    lst <- list(
      abc_df1 = data.frame(x = 1:3),
      def_df2 = data.frame(y = 4:6),
      abc_test = data.frame(z = 7:9),
      normal_df = data.frame(a = 10:12)
    )
    
  • 提取名称包含'abc'的元素:

    # 用str_detect检测元素名称是否含'abc',得到逻辑向量
    keep_indices <- str_detect(names(lst), "abc")
    # 筛选列表
    filtered_lst <- lst[keep_indices]
    
  • 一行搞定的简化写法:

    filtered_lst <- lst[str_detect(names(lst), "abc")]
    

如果不想用stringr,基础R的grepl也能实现同样效果,写法类似:

filtered_lst <- lst[grepl("abc", names(lst))]

内容的提问来源于stack exchange,提问作者Shaggy Glitch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:57:32