Brani Brani - 26 days ago 17
R Question

dplyr: How to apply the same filter to all variables

I am sure there must be a better way to do the following:

library(dplyr)
df %>%
filter(X1 %in% c(0,1,2,5,10) &
X2 %in% c(0,1,2,5,10) &
X3 %in% c(0,1,2,5,10) &
X4 %in% c(0,1,2,5,10) &
X5 %in% c(0,1,2,5,10) &
X6 %in% c(0,1,2,5,10) &
X7 %in% c(0,1,2,5,10) &
X8 %in% c(0,1,2,5,10) &
X9 %in% c(0,1,2,5,10) &
X10 %in% c(0,1,2,5,10) &
X11 %in% c(0,1,2,5,10) &
X12 %in% c(0,1,2,5,10) &
X13 %in% c(0,1,2,5,10) &
X14 %in% c(0,1,2,5,10) &
X15 %in% c(0,1,2,5,10) &
X16 %in% c(0,1,2,5,10) &
X17 %in% c(0,1,2,5,10) &
X18 %in% c(0,1,2,5,10) &
X19 %in% c(0,1,2,5,10) &
X20 %in% c(0,1,2,5,10) )

Answer

From comments above, the following works.

df[apply(df, 1, function(x) all(sapply(x, function(y) y %in% c(0, 1, 2, 5, 10)))), ]
Comments