Reputation: 33
I have browsed the other answers regarding issues with plyr and dplyr without success.
I want to use two inputted variables in the dplyr "group_by_" and "summarise" commands. I can not seem to find the right syntax to input my variable into summarise to get a mean with the grouping. Turning it back into a data frame doesn't work.
new_frame <- frame()
new_frame[[input$ycol]]
sapply gives a result but it ignores the grouping levels and gives me the mean of the entire column.
mean = sapply(frame()[input$ycol],mean)
I am not sure what other options to use.
MWE with error as follows.
library(shiny)
ui <- fluidPage(
titlePanel("MWE using faithful data"),
sidebarLayout(
sidebarPanel(
selectInput('xcol', 'X Variable', "",choices = "colour"),
selectInput('ycol', 'Y Variable', "",choices = c("waiting", "eruptions"))),
mainPanel(
tableOutput("distPlot"))))
server <- function(input, output) {
frame <- reactive({
faithful <- faithful %>% mutate(colour = rep(c("red","white"),136))
return(faithful)
})
output$distPlot <- renderTable({
frame() %>% group_by_(input$xcol) %>%
summarise(mean = mean(input$ycol))
})
}
shinyApp(ui = ui, server = server)
If I hard code the line
summarise(mean = mean(input$ycol))
to
summarise(mean = mean(eruptions))
Using summarise_ is no good either.
it gives me what I want, but that is not an option in my actual code. Any help would be appreciated.
Thanks
Upvotes: 2
Views: 1571
Reputation: 887961
The main problem is how we are evaluating the input$xcol
and input$ycol
. These are string elements. One option is to convert it to symbol with rlang::sym
and evalute with !!
library(shiny)
library(dplyr)
ui <- fluidPage(
titlePanel("MWE using faithful data"),
sidebarLayout(
sidebarPanel(
selectInput('xcol', 'X Variable', "",choices = "colour"),
selectInput('ycol', 'Y Variable', "",choices = c("waiting", "eruptions"))),
mainPanel(
tableOutput("distPlot"))))
server <- function(input, output) {
frame <- reactive({
faithful %>%
mutate(colour = rep(c("red","white"),136))
})
output$distPlot <- renderTable({
frame() %>%
group_by(!! rlang::sym(input$xcol)) %>%
summarise(mean = mean(!! rlang::sym(input$ycol)))
})
}
shinyApp(ui = ui, server = server)
-output
Upvotes: 3