基于列名的子集列

问题描述 投票:0回答:3

我有一个带有ID的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部分匹配的列

code

using dplyr

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

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

using 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
r dplyr
3个回答
1
投票

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

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

这将来自IDdf1s与|作为分隔符(意思是逻辑OR)粘贴在一起,如下所示:

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

这是必要的,因为matches然后查找匹配这些数字中的一个或另一个的列名称,然后这些列是selected。 dplyrselect以及matches都需要%>%


1
投票

由于列名称中有明确的模式,您可以使用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]


0
投票

在df1中,“text”列是整数类型。

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)
© www.soinside.com 2019 - 2024. All rights reserved.