Display a summary of a variable in a shiny app (summary() )

Viewed 610

Does anyone know how I can display a summary created by summary() in a shiny app? So that the descriptions of the values (e.g. "mean", "median") are also displayed.

I've tried it with verbatimTextOutput() so far.

library(shiny)

# FAKE DATAFRAME
data <- reactive(  
    data.frame(
        group = sample(c("A", "B"), 100, replace = TRUE),
        var1 = round(runif(100, min = 0, max = 100), 0),
        var2 = sample(c("A", "B"), 100, replace = TRUE)
    )
)

# USER INTERFACE
ui <- fluidPage(
    verbatimTextOutput("text1")
)

# SERVER
server <- function(input, output) {
    output$text1 <- renderText({
        summary(data()$var1)
    })
}

# START APP
shinyApp(ui = ui, server = server)

Thanks for help!

1 Answers

This could be achieved via tableOutput and renderTable like so. The first approach converts the summary() output to a tibble via tibble::enframe which gives you a column-wise table with the first column containing the name of the summary statistics, while the second approach using tibble::tibble gives you a rowwise table with the first row containing the name of the summary statistics. Try this:

library(shiny)
library(tibble)
# FAKE DATAFRAME
data <- reactive(  
  data.frame(
    group = sample(c("A", "B"), 100, replace = TRUE),
    var1 = round(runif(100, min = 0, max = 100), 0),
    var2 = sample(c("A", "B"), 100, replace = TRUE)
  )
)

# USER INTERFACE
ui <- fluidPage(
  tableOutput("text1"),
  tableOutput("text2")
)

# SERVER
server <- function(input, output) {
  output$text1 <- renderTable({
    tibble::enframe(summary(data()$var1))
  })
  output$text2 <- renderTable({
    tibble::tibble(!!!summary(data()$var1))
  })
}

# START APP
shinyApp(ui = ui, server = server)
Related