Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `dplyr::filter_at` with multiple predicate expression

Tags:

r

dplyr

tidyverse

Consider the following tibble.

 # A tibble: 5 x 3
 g1    g2     a
 <dbl> <dbl> <int>
  1     1     1     1
  2     1    NA     2
  3     2     1     3
  4     2     2     4
  5     2     2     5

I want to keep the rows if and only if (a) g1 == 1 and g2 == 1 and (b) g1 and g2 are not missing values. I can do this with filter_at and all_vars. See below.

df <- tibble(
  g1 = c(1, 1, 2, 2, 2),
  g2 = c(1, NA, 1, 2, 2),
  a = c(1 : 5)
)
df %>% filter_at(vars(starts_with("g")), all_vars(. == 1)) %>%
    filter_at(vars(starts_with("g")), all_vars(!is.na(.)))

My question is how to combine the two filter_at lines above into something like the following:

df %>% filter_at(vars(starts_with("g")), all_vars(. == 1) & all_vars(!is.na(.)))

It seems all_vars or any_vars can take only one expression.

like image 726
semibruin Avatar asked Nov 21 '25 20:11

semibruin


1 Answers

You can use & inside all_vars() to use multiple conditions.

df %>%
     filter_at(vars(starts_with("g")), all_vars(. == 1 & !is.na(.) ) )

# A tibble: 1 x 3
     g1    g2     a
  <dbl> <dbl> <int>
1     1     1     1
like image 113
aosmith Avatar answered Nov 23 '25 10:11

aosmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!