【发布时间】: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 %>% select(matches(paste(df1$ID, collapse = "|")))怎么样? -
从哪个模块中选择和匹配给我和错误
could not find function "matches" -
对不起,我是
dplyr。 -
@Lyngbakr 方法有效,并且将简洁的注意事项作为答案?