Shiny Table output of summary stats of user selected column

Appreciate any help with this. I am trying to summarize a table based on user selected group by column. The following code throws an error
Warning: Error in as.data.frame.default: cannot coerce class ‘c("reactiveExpr", "reactive")’ to a data.frame. I am running R 3.6 & RStudio on windows.



library(shiny)
library(dplyr)

df <- data.frame(grouping_letter = c('A', 'A', 'B', 'B', 'C', 'C'), 
                 grouping_animal = c('Cat', 'Dog', 'Cat', 'Dog', 'Cat', 'Dog'),
                 value = c(1,2,3,4,5,6))

df <- df %>% mutate(
    grouping_letter = as.character(grouping_letter),
    grouping_animal = as.character(grouping_animal))

# Define UI for application that summarizes a table
ui <- fluidPage(

    selectInput(inputId ="column",
                label = "Choose Column for Summary",
                choices = names(df),
                selected = "grouping_letter"),
    
    tableOutput('table')
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    # cols <- c('value', !! sym(input$column))
    dt_f <- reactive({
        req(input$column)
        df%>%
        group_by(!! sym(input$column)) %>%
        summarise (value = n(), yield = round(mean(value)*100, 1)) %>%
        mutate(Pct_of_value = paste0(round(100 * value/sum(value), 0), "%"))
})
    output$table <- renderTable(dt_f)
}

# Run the application 
shinyApp(ui = ui, server = server)

Hi @DS_guy. The error come from dt_f missing blanket.

output$table <- renderTable(dt_f())

And the input$column also cause error when choosing value, remove the choices of value will do.

Thank You! I was able to solve it. Here is the solution:

library(shiny)
library(dplyr)

df <- data.frame(grouping_letter = c('A', 'A', 'B', 'B', 'C', 'C'), 
                 grouping_animal = c('Cat', 'Dog', 'Cat', 'Dog', 'Cat', 'Dog'),
                 value = c(1,2,3,4,5,6))

df <- df %>% mutate(
    grouping_letter = as.character(grouping_letter),
    grouping_animal = as.character(grouping_animal))

# Define UI for application that summarizes a table
ui <- fluidPage(

    selectInput(inputId ="column",
                label = "Choose Column for Summary",
                choices = names(df),
                selected = "grouping_letter"),
    
    tableOutput('table')
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    dt_f <- reactive({
        req(input$column)
        df%>%
        group_by(!!sym(input$column)) %>%
        summarise (value = n(), yield = round(mean(value)*100, 1)) %>%
        mutate(Pct_of_value = paste0(round(100 * value/sum(value), 0), "%"))
})
    output$table <- renderTable(dt_f())
}

# Run the application 
shinyApp(ui = ui, server = server)

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