首页 > 解决方案 > 基于列名的子集列

问题描述

我有一个带有 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

标签: rdplyr

解决方案


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

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

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

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

这是需要的,因为matches然后查找与这些数字中的一个或另一个匹配的列名称,然后select编辑这些列。dplyr需要select,matches%>%.


推荐阅读