如何在 R shiny 中更改 table 的格式

How to change format of table in R shiny

我正在尝试生成以下 table 作为 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)

但是数据输出格式如下:

Var1 Var2 Freq
Population (m) France 67
Size (km) France 543940
No. of cities France 85

相反,我希望 table 显示为:

France
Population (m) 67
Size (km) 543940
No. of cities 85

我如何在 R shiny 中执行此操作?

您可以考虑使用库(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)

您不应使用 as.table() 函数,因为这似乎会产生问题。要显示行名,请将行名参数设置为 TRUE:

renderTable(data,rownames = TRUE)

完整代码:

服务器:

library(shiny)
## Server:
shinyServer(function(input, output) {

  data <- matrix(c(67,543940,85),ncol = 1,byrow = T)
  colnames(data) <- "France"
  rownames(data) <- c("Population (m)", "Size (km)", "No. of cities")
  # this line is not needed and causes the "error"
  # summary <- as.table(data)
  output$table <- renderTable(data,rownames = TRUE)
  

})

ui:

## UI:

shinyUI(fluidPage(
  fluidRow(
           tableOutput('table')
    )
  )
)

这会给你想要的结果