Ai4l2s
Ai4l2s

Reputation: 623

R: Group_by depending on condition

let's assume I have this simple dataframe:

df <- tibble(a = c(1, 1), b = c(2, 2))

I now want to know how to use a group_by inside a pipline that depends on a variable. Something like,

flag <- T
resulting <- df %>% 
              filter(a > 0 & b >0) %>%
              group_by(ifelse(flag), yes = c(a), no = c(a, b))

That is, if flag == T, then I want to group only on column a. If flag is false I want to group an both columns.

Upvotes: 0

Views: 53

Answers (1)

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

I think this worked for me

flag <- T
resulting <- df %>% 
    filter(a > 0 & b >0) %>%
    {if(flag) group_by(.,a) else group_by(. ,a , b)}

resulting

# A tibble: 2 × 2
# Groups:   a [1]  # <======== here grouped by a
      a     b
  <dbl> <dbl>
1     1     2
2     1     2

by changing the flag

flag <- F
resulting <- df %>% 
    filter(a > 0 & b >0) %>% 
    {if(flag) group_by(.,a) else group_by(. ,a , b)}

resulting

# A tibble: 2 × 2
# Groups:   a, b [1]   # <======== here grouped by a ,b
      a     b
  <dbl> <dbl>
1     1     2
2     1     2

Upvotes: 2

Related Questions