简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM