Reputation: 21928
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
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.
Upvotes: 4
Views: 429
Reputation: 887391
We can use if_all
library(dplyr)
df %>%
filter(across(where(is.numeric), ~ . > 0)|
if_all(where(is.numeric), ~ . < 0))
-output
# A tibble: 2 x 4
# x y z p
# <chr> <dbl> <dbl> <dbl>
#1 a 1 1 1
#2 b -1 -1 -1
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)))
-output
# A tibble: 2 x 4
# x y z p
# <chr> <dbl> <dbl> <dbl>
#1 a 1 1 1
#2 b -1 -1 -1
Upvotes: 6