How can I specify columns in R to be used in matches (without listing each individually)?

删除回忆录丶 提交于 2019-12-25 16:42:38

问题


Suppose I have three columns of data (sample1, sample2, and sample3). I want all of the rows in which the letter b or h appears in any one of the columns. This works fine:

data <- data.frame(row_name=c("s1_100","s1_200", "s2_300", "s1_400", "s1_500"), 
                   sample1=rep("a",5),
                   sample2=c(rep("b",2),rep("a",3)),
                   sample3=c(rep("a",4),"h")
)

data

# row_name  sample1   sample2   sample3
# s1_100    a         b         a
# s1_200    a         b         a
# s1_300    a         a         a
# s1_400    a         a         a
# s1_500    a         a         h

bh <- c('b','h')
bh_data <- subset(data, ( sample1 %in% bh | sample2 %in% bh | sample3 %in% bh )  )

bh_data

# row_name  sample1   sample2   sample3
# s1_100    a         b         a
# s1_200    a         b         a
# s1_500    a         a         h

However, since I'm asking the same question about each column, isn't there a less redundant way to do this?

But in reality, we have over 800 columns and over 70,000 rows, and we will want to be able to choose as many or as few specific columns to search. Using hundreds of column names for example, just doesn't seem practical unless I script creating the R script.


回答1:


Try

 indx <- Reduce(`|`, lapply(df[,-1], `%in%`, bh))
 df[indx,]
 #   row_name sample1 sample2 sample3
 #1   s1_100       a       b       a
 #2   s1_200       a       b       a
 #5   s1_500       a       a       h

Or using data.table

 library(data.table)
 nm1 <- paste0("sample", 1:3)
 setDT(df)[df[, Reduce(`|`,lapply(.SD, `%in%`, bh)), .SDcols=nm1]]
 #    row_name sample1 sample2 sample3
 #1:   s1_100       a       b       a
 #2:   s1_200       a       b       a
 #3:   s1_500       a       a       h

data

 df <- structure(list(row_name = c("s1_100", "s1_200", "s1_300", "s1_400", 
 "s1_500"), sample1 = c("a", "a", "a", "a", "a"), sample2 = c("b", 
 "b", "a", "a", "a"), sample3 = c("a", "a", "a", "a", "h")), .Names = c("row_name", 
 "sample1", "sample2", "sample3"), class = "data.frame", row.names = c(NA, 
 -5L))


来源:https://stackoverflow.com/questions/26305233/how-can-i-specify-columns-in-r-to-be-used-in-matches-without-listing-each-indiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!