Group_by() if FALSE within Reactive Expression

Hey Everyone,

I'm attempting to use to create a reactive expression which does a group_by() when a certain radio button is False, and does a total aggregation otherwise. I have tried doing this with both ifelse and case_when functions, but have not had any success. Any tips/ideas?

Ultimately I am trying to pipe this into a gt table which will again show split out via tab_stubhead() by group if the the radio button if false, and total aggregation otherwise.

Best,
Matt

Hi, the group_by() can be left blank and the summarization will be done for the entire data set. Using this capability, you can use rlang to create a function that passes the grouping variable, something like this:

library(dplyr)
library(rlang)

my_function <- function(x)  {
  mtcars %>% 
    group_by({{x}}) %>% 
    summarise(avg_wt = mean(wt))
}

my_function()
#> # A tibble: 1 x 1
#>   avg_wt
#>    <dbl>
#> 1   3.22

my_function(am)
#> # A tibble: 2 x 2
#>      am avg_wt
#>   <dbl>  <dbl>
#> 1     0   3.77
#> 2     1   2.41
2 Likes

Hi,

Welcome to the RStudio community!

Based off a post I found here, I think this might be a way to accomplish this:

library(dplyr)

condition = T

test = iris %>%
  {if(condition) group_by(., Species) else .} %>% 
  summarise(n = n())
test
#> # A tibble: 3 x 2
#>   Species        n
#>   <fct>      <int>
#> 1 setosa        50
#> 2 versicolor    50
#> 3 virginica     50

          
condition = F

test = iris %>%
  {if(condition) group_by(., Species) else .} %>% 
      summarise(n = n())
test
#>     n
#> 1 150

Created on 2021-07-01 by the reprex package (v2.0.0)

I'm not a big fan of this notation, so I would normally just split up the code in two steps.

PJ

1 Like

Thank you for this response. Can this be done outside of an explicit function call, and in a reactive expression?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.