我很好奇实现这一目标的一种更简洁的方法:
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”使用字符串匹配,而不必为每个列名写不同的条件吗?
答案 0 :(得分:2)
您可以将filter_at
与ends_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))