在 dplyr Column-wise 操作中有这个例子:
df <- tibble(x = c("a", "b"), y = c(1, 1), z = c(-1, 1))
# Find all rows where EVERY numeric variable is greater than zero
df %>% filter(across(where(is.numeric), ~ .x > 0))
#> # A tibble: 1 x 3
#> x y z
#> <chr> <dbl> <dbl>
#> 1 b 1 1
如果我们稍微改变一下小标题:
df <- tibble(x = c("a", "b", "c"), y = c(1, 1, -1), z = c(-1, 1, -1))
我们想要为两列获取负值或正值,我们需要命名列:
df %>% filter((y > 0 & z > 0) | (y < 0 & z < 0))
#> # A tibble: 2 x 3
#> x y z
#> <chr> <dbl> <dbl>
#> 1 b 1 1
#> 2 c -1 -1
如何across()
做到这一点?
df %>% filter(across(where(is.numeric), ~ .x > 0 | .x < 0))
#> # A tibble: 3 x 3
#> x y z
#> <chr> <dbl> <dbl>
#> 1 a 1 -1
#> 2 b 1 1
#> 3 c -1 -1