'How to change format of table in R shiny
I am trying to generate the following table as a output in R shiny:
data <- matrix(c(67,543940,85),ncol = 1,byrow = T)
colnames(data) <- "France"
rownames(data) <- c("Population (m)", "Size (km)", "No. of cities")
summary <- as.table(data)
output$table <- renderTable(summary)
However the data is outputted in the following format:
| Var1 | Var2 | Freq |
|---|---|---|
| Population (m) | France | 67 |
| Size (km) | France | 543940 |
| No. of cities | France | 85 |
Instead I want it the table to be displayed as:
| France | |
|---|---|
| Population (m) | 67 |
| Size (km) | 543940 |
| No. of cities | 85 |
How would I do this in R shiny?
Solution 1:[1]
You may consider using library(gt) https://gt.rstudio.com/index.html
library(gt)
library(shiny)
library(tidyverse)
#############################################
#load your data here
data <- data.frame(Var1 = c("Population (m)", "Size (km)", "No. of cities"),
Var2 = rep('France', 3),
Freq = c(67, 543940, 85))
dataLong <- data %>%
pivot_longer(cols = Freq,
names_to = ".value")
#############################################
# Define UI for application
#############################################
ui <- fluidPage(
"My Shiny App",
gt_output('table')
)
#############################################
# Define server logic
#############################################
server <- function(input, output) {
output$table <- render_gt(
gt(dataLong) %>%
tab_spanner(label = unique(dataLong$Var2),
columns = Freq) %>%
cols_hide(Var2) %>%
cols_label(Var1 = '',
Freq = ' ')
)
}
# Run the application
shinyApp(ui = ui, server = server)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Susan Switzer |

