Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using dplyr filter_at() function to select rows with conditions

Tags:

r

filter

dplyr

I want to filter data frame according to a specific conditions in several columns.

I use the following example o make it my statement more clear.

I have a data frame:

dat <- data.frame(A = c(122, 122, 122), B = c(0.1, 0.1, 0.1), 
                  C = c(5, 5, 4), D = c(6, 7, 6))

I want to select rows which contains both maximum values in column C and D, my R code is :

select <- dat %>%
          group_by(A, B) %>%
          filter(C == max(C) , D == max(D))

and I get want I want:

> select
# A tibble: 1 x 4
# Groups:   A, B [1]
     A     B     C     D
   <dbl> <dbl> <dbl> <dbl>
1   122   0.1     5     7 

However, I want to use filter_at() function

select <- dat %>%
          group_by(A, B) %>%
          filter_at(vars(C, D), all_vars(. max))

It did not work. Thanks a lot for your help.

like image 358
Wang Avatar asked Jan 20 '26 13:01

Wang


1 Answers

You can do this:

dat %>%
    group_by(A, B) %>%
    filter_at(vars(C, D), all_vars(. == max(.)))

The problem before was all_vars() is expecting to evaluate to a logical. And without an equality operator, ==, >, <, it was throwing an error back at you.

like image 136
Nate Avatar answered Jan 23 '26 19:01

Nate