 # Group By Nest in Shiny

Hi Friends ,
Can you please help to correct the errors in below code as im unable to use group_by and nest in shiny. Below is simplified example.

``````library(tidyverse)
library(shiny)

x<-rnorm(10,100,20)
y<-c("a","a","a","a","a","b","b","b","b","b")
t<-data.frame(x,y)

ui<-fluidPage(

mainPanel(
selectInput("Grp","Input Group",choices=names(t)),
tableOutput("table_1")
)
)

Fraction<-function(df){
df/sum(df)
}
server <-function(input,output){
nested<-reactive({
req(input\$Grp)
t %>%
group_by(input\$Grp)%>%
nest()
})

output\$table_1<-renderTable({
map(nested()\$data,Fraction)
})

}
shinyApp(ui=ui,server=server)
'''

----------------------
The normal R code works fine  that is similar to above
x <- rnorm(10, 100, 20)
y <- c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b")
t <- data.frame(x, y)
t1 <- t %>% group_by(y) %>% nest()
Fraction <- function(df) {
df / sum(df)
}
t2 <- map(t1\$data, Fraction)
t2``````

in your working code, group_by(y) works where y is the symbol for the name to group on, but in your shiny app input\$Grp is itself a symbol (one not present in your t df.
the value of input\$Grp might be "y" , to 'get at it' use library(rlang)

`````` t %>%
group_by(!!sym(input\$Grp))%>%
nest()
``````

Hi Sir ,
Thanks for prompt help any resources u can recommend where such differences between R and Shiny can be found.

Its not really a difference.
input\$Grp is like any variable in base R as far as the group by is concerned

in base R without shiny if you had

``````x <- rnorm(10, 100, 20)
y <- c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b")
t <- data.frame(x, y)
variable_to_group_by <- "y"

#would fail
t1 <- t %>% group_by(variable_to_group_by ) %>% nest()
#would work
t1 <- t %>% group_by(!!sym(variable_to_group_by )) %>% nest()``````
1 Like

You can have a look here at shiny specifically: https://mastering-shiny.org/
and then on the !! (bang bang operator) you can have a look here: https://adv-r.hadley.nz/meta-big-picture.html this relates to normal R but can be used in shiny as @nirgrahamuk showed.

1 Like

Here, you are briefly touching the subject of tidy evaluation or programming in dplyr. Your shiny input variable input\$Grp is a string (as nirgrahamuk already mentioned) which you need to convert into a symbol to mimick typing y (as in your explicit example).

1 Like

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.