r - 基于列名的子集列
问题描述
我有一个带有 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
解决方案
这是使用该dplyr
包的解决方案。
df2 %>% select(matches(paste(df1$ID, collapse = "|")))
这将ID
s from df1
with|
作为分隔符(意思是逻辑OR
)粘贴在一起,如下所示:
"8765|1879|8706|1872|178|268|270|269|61|271"
这是需要的,因为matches
然后查找与这些数字中的一个或另一个匹配的列名称,然后select
编辑这些列。dplyr
需要select
,matches
也%>%
.
推荐阅读
- html - CSS :hover text-decoration: 下划线在 Safari 上不起作用
- python - 与列表元素部分匹配的文件名
- reactjs - OnChange 中缺少 React State 字段
- flutter - 参数类型“用户?函数(用户)”不能分配给参数类型“用户?函数(用户?)”
- date - Google App Script - 如何在 AdminReports.UserUsageReport.get() 中使用时区设置日期
- python - KivyMD RecycleView 网格中的复选框操作重复
- git - 执行 git push 时,Git bash 卡住了
- excel - 是否可以使用 VBA 宏始终检查您刚刚编辑的每个单元格,然后将其着色为某种颜色(如果是硬编码或公式)?
- excel - 事件 Worksheet_BeforeDoubleClick 提供先前双击的值
- python - 无法使用 Google 的规范示例从 Bigtable 读取数据