df <- data.frame(x = c(1,2,3,4), y = c(1,2,3,4), z = c("A","B","A","B"))
我正在尝试使用
dplyr
的 filter
函数来过滤总和大于 4 的行。
我试过:
df %>% filter_at(vars(c(x,y)), any_vars(rowSums(.) > 4))
Error in `filter()`:
ℹ In argument: `rowSums(x) > 4 | rowSums(y) > 4`.
Caused by error in `rowSums()`:
! 'x' must be an array of at least two dimensions
Run `rlang::last_trace()` to see where the error occurred.
所需输出:
x y z
3 3 A
4 4 B
我不知道如何使用 rowSums 来做到这一点,主要是因为它需要两个输入,并且当您使用 filter_if 或 if_any() 时,您将逐一传递一列作为列表
但是下面的方法可以工作
library(tidyverse)
df |>
rowwise() |>
mutate(
row_total=sum(c_across(x:y))
) |>
filter(row_total>5) |>
select(-row_total)