如何使用字符串名称匹配的dplyr过滤多列?

时间:2020-05-17 15:39:22

标签: r dplyr

我很好奇实现这一目标的一种更简洁的方法:

nyc_crashes %>% filter(
  `NUMBER OF PERSONS INJURED`     >= 1 |
  `NUMBER OF PERSONS KILLED`      >= 1 |
  `NUMBER OF PEDESTRIANS INJURED` >= 1 |
  `NUMBER OF PEDESTRIANS KILLED`  >= 1 |
  `NUMBER OF CYCLIST INJURED`     >= 1 |
  `NUMBER OF CYCLIST KILLED`      >= 1 |
  `NUMBER OF MOTORIST INJURED`    >= 1 |
  `NUMBER OF MOTORIST KILLED`     >= 1
)

我可以对“ INJURED | KILLED”使用字符串匹配,而不必为每个列名写不同的条件吗?

1 个答案:

答案 0 :(得分:2)

您可以将filter_atends_with一起使用。

library(dplyr)
nyc_crashes %>%
  # Select columns that end with KILLED or INJURED
  filter_at(vars(c(ends_with("KILLED"),ends_with("INJURED"))), 
            # Keep rows where any of these variables is >= 1 
                          any_vars(. >= 1))