dplyr:如何将相同的过滤器应用于所有变量

时间:2016-11-07 20:04:37

标签: r dplyr

我确信必须有更好的方法来执行以下操作:

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

1 个答案:

答案 0 :(得分:3)

根据以上评论,以下内容有效。

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