且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 pmap 函数检查一行中的所有值是正数还是负数

更新时间:2022-04-12 22:05:28

我们可以使用if_all

library(dplyr)
df %>% 
    filter(across(where(is.numeric), ~ . > 0)|
           if_all(where(is.numeric), ~ . < 0))

-输出

# A tibble: 2 x 4
#  x         y     z     p
#  <chr> <dbl> <dbl> <dbl>
#1 a         1     1     1
#2 b        -1    -1    -1


或者使用 pmap 通过 selecting numeric 列,检查 all 的值是否小于 0或 | 大于 0


Or with pmap by selecting the numeric columns, check whether all the values are less than 0 or | greater than 0

library(purrr)
df %>%
   filter(pmap_lgl(select(., where(is.numeric)), 
              ~ all(c(...) < 0)| all(c(...)> 0)))

-输出

# A tibble: 2 x 4
#  x         y     z     p
#  <chr> <dbl> <dbl> <dbl>
#1 a         1     1     1
#2 b        -1    -1    -1