【问题标题】:subset columns based on column names基于列名的子集列
【发布时间】:2018-08-14 16:58:46
【问题描述】:

我有一个带有 ids 的 df1

df1 <- read.table(text="ID
8765
                    1879
                    8706
                    1872
                    0178
                    0268
                    0270
                    0269
                    0061
                    0271", header=T)

第二个带有列名的 df2

> names(df2)
 [1] "TW_3784.IT"   "TW_3970.IT"   "TW_1879.IT"   "TW_0178.IT"   "SF_0271.IT" "TW_3782.IT"  
 [7] "TW_3783.IT"   "TW_8765.IT"   "TW_8706.IT"   "SF_0268.IT" "SF_0270.IT" "SF_0269.IT"
[13] "SF_0061.IT"

我需要的是只保留 df2 中与 df1 部分匹配的列

代码

使用 dplyr

df3 = df2 %>% 
  dplyr::select(df2 , dplyr::contains(df1$ID))
error

Error in dplyr::contains(df1$ID) : is_string(match) is not TRUE

使用 grepl

df3 = df2[,grepl(df1$ID, names(df2))]

error
In grepl(df1$ID, names(df2)) :
  argument 'pattern' has length > 1 and only the first element will be used

【问题讨论】:

  • 只返回NULL
  • df2 %&gt;% select(matches(paste(df1$ID, collapse = "|"))) 怎么样?
  • 从哪个模块中选择和匹配给我和错误could not find function "matches"
  • 对不起,我是dplyr
  • @Lyngbakr 方法有效,并且将简洁的注意事项作为答案?

标签: r dplyr


【解决方案1】:

这是一个使用 dplyr 包的解决方案。

df2 %>% select(matches(paste(df1$ID, collapse = "|")))

这会将df1 中的IDs 与| 作为分隔符(意思是逻辑OR)粘贴在一起,如下所示:

"8765|1879|8706|1872|178|268|270|269|61|271"

这是必需的,因为matches 然后查找与这些数字中的一个或另一个匹配的列名称,然后这些列是 selected。 dplyr 需要 selectmatches%&gt;%

【讨论】:

    【解决方案2】:

    由于列名中有一个清晰的模式,您可以使用substr 提取每个 4 位 ID。将其转换为数字以删除前导零。使用which 标识您要保留的列号。

    df2 <- c("TW_3784.IT", "TW_3970.IT", "TW_1879.IT", "TW_0178.IT", "SF_0271.IT", "TW_3782.IT")
    
    numbers <- which(as.numeric(substr(df2, 4, 7)) %in% df1[,1])
    

    接下来,您可以使用这些列号对数据框进行子集化:df[,numbers]

    【讨论】:

      【解决方案3】:

      在 df1 中,您的“文本”列是整数类型。

      str(df1)
      'data.frame':   10 obs. of  1 variable:
       $ ID: int  8765 1879 8706 1872 178 268 270 269 61 271
      

      转换为字符串,is_string() 应该返回 true。

      b6$ID <- as.character(b6$ID)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-09
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        相关资源
        最近更新 更多