Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select rows comparing multiple columns with the same value?

Tags:

r

data.table

Suppose I have the following data and a vector of column names

dt <- data.table(id = letters[1:10], amount = 1:10, id2 = c(rep('a',5),rep('b',5)),test=rep('a',10))
cols <- c('id','id2','test')

what I'm trying to do is select rows where all columns in the vector have the same specific value like

dt[id=='a' & id2=='a' & test == 'a']

but using the vector cols. Is there a way to do it?

Note: I need to find a way to do it using data.table or base R without making comparisons between the columns like

dt[id==id2 & id==test & id2==test]
like image 924
R. Cowboy Avatar asked Aug 06 '26 09:08

R. Cowboy


1 Answers

You can take help of .SDcols -

library(data.table)

dt[dt[, rowSums(.SD == 'a') == length(cols), .SDcols = cols]]

#   id amount id2 test
#1:  a      1   a    a

This can also be written as -

dt[rowSums(dt[, ..cols] == 'a') == length(cols), ]
like image 164
Ronak Shah Avatar answered Aug 08 '26 23:08

Ronak Shah