I have a shiny app where the ungrouping is not working properly when I compare the result from "un-shiny" version of the output with the tableOutput
in Shiny. I was expecting both to have a same result. Please see this for reference:
# "un-shiny" version to compare results, not part of the app.
# This is to match with mpg input in shiny
mtcars %>%
select(mpg, cyl, disp,
wt, gear) %>%
mutate(wt = as.integer(wt),
mpg =as.integer(mpg)) %>%
filter(gear >= 4 & gear <= 5) %>%
group_by(wt,gear, mpg) %>%
tally() %>%
ungroup() %>%
group_by(gear,mpg) %>%
rename(Count= n)%>%
mutate(summ = sum(Count),
Percentage = round((Count/summ)*100, 2))
Now, in the shiny app-
library(dplyr)
library(tidyr)
library(shiny)
#global.R -----
mtcars_rdpr <- mtcars %>%
select(mpg, cyl, disp,
wt, gear) %>%
mutate(wt = as.integer(wt),
mpg =as.integer(mpg)) %>%
filter(gear >= 4 & gear <= 5) %>%
#ui.R ----
ui <- fluidPage(
sidebarLayout(
mainPanel(
selectInput("pickvalue", label = "Gears", colnames(mtcars_rdpr%>%
select(mpg, cyl)),
selected = NULL, multiple = F)),
tableOutput("tableOut")
)
)
# server.R-----
server <- function(input, output, session){
gears <- reactive({
dat <- mtcars_rdpr
if (!is.null(input$pickvalue)){
dat <- dat %>%
group_by(wt,gear, input$pickvalue) %>%
tally() %>%
ungroup() %>% # when i mention specific columns in the function, I get a warning
group_by(gear,input$pickvalue) %>%
rename(Count= n)%>%
mutate(summ = sum(Count),
Percentage = round((Count/summ)*100, 2))
}
#dat <- dat %>% select(-input$pickvalue) # this gives a warning
return(dat)
})
output$tableOut<- renderTable({gears()})
}
shinyApp(ui = ui, server=server)
I would really appreciate it if someone can explain to me why the results are not matching between the two.
CodePudding user response:
You cannot mix up non-standard evaluation with character strings, which you essentially did in your code.
As of dplyr 1.0.0, you can use across and combine them in a vector:
Just the relevant line:
group_by(across(c("gear", input$value))) %>%