2

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!

D. Studer
  • 1,711
  • 1
  • 16
  • 35

1 Answers1

1

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)
stefan
  • 90,330
  • 6
  • 25
  • 51
  • Can you explain the three bangs in `!!!summary(data()$var1)`? – cbrnr Mar 11 '22 at 07:10
  • 1
    @cbrnr `!!!` is the so called splice operator. See "?\`!!!\`". Basically `!!!` converts a named vector into a list of named arguments, e.g. `tibble::tibble(!!!c(a = 1, b = 2))` is the same as `tibble::tibble(a = 1, b = 2)`. In the answer I make use of `!!!` to get a nice summary table where each summary stat is put in its own column. Without `!!!` I would get a tibble where the summary stats will be in one column instead. – stefan Mar 11 '22 at 07:30