问题描述
我有这个数据框,我想单独使用 pmap
函数来过滤所有值为负或正的行.我正在寻找一种简洁的方法来做到这一点,因为我想到了 c(...)
但我们只能在函数中使用它.可以通过以下代码实现:
I have this data frame and I would like to solely use pmap
function to filter only rows where all values are either negative or positive. I am looking for a concise way of doing this as I thought about c(...)
but we can only use it inside a function.It is achievable by this code:
df <- tibble(x = c("a", "b", "c"), y = c(1, -1, -1), z = c(1, -1, 1),
p = c(1, -1, -1))
df %>%
filter(pmap_lgl(list(y, z, p), ~ ..1 > 0 & ..2 > 0 & ..3 > 0 |
..1 < 0 & ..2 < 0 & ..3 < 0))
# A tibble: 2 x 4
x y z p
<chr> <dbl> <dbl> <dbl>
1 a 1 1 1
2 b -1 -1 -1
所以我正在寻找一种将谓词应用于所有值的方法,以防我有超过 3 列我不想命名它们或像这样引用它们.
So I am looking for a way that predicate applies on all values in case I had more than 3 columns that I don't want to name them or refer to them like this.
任何帮助将不胜感激,并提前感谢您.
Any help would be highly appreciated and thank you in advance.
推荐答案
我们可以使用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
通过 select
ing numeric
列,检查 all
的值是否小于 0或 |
大于 0
Or with pmap
by select
ing 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
这篇关于使用 pmap 函数检查一行中的所有值是正数还是负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!