簡體   English   中英

基於列名的子集列

[英]subset columns based on column names

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

使用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

由於列名中有清晰的圖案,因此可以使用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]

這是使用dplyr軟件包的解決方案。

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

df1ID|粘貼在一起| 像這樣的分隔符(意思是邏輯OR ):

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

這是必需的,因為matches然后查找與這些數字中的一個或另一個匹配的列名,然后select這些列。 selectmatches以及%>%都需要dplyr

在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM