我正在尝试在 Shiny 应用程序中上传两个 Excel 文件。上传后它应该显示
head
那些文件。我正在尝试以下块:
library(shiny)
library(readxl)
# UI component
ui <- fluidPage(
titlePanel("Upload Excel file"),
sidebarLayout(sidebarPanel(
fileInput('file1', 'Choose first file',
accept = c(".xlsx"),
buttonLabel = "Upload",
multiple = TRUE),
fileInput('file2', 'Choose second file',
accept = c(".xlsx"),
buttonLabel = "Upload",
multiple = TRUE)
),
mainPanel(
tableOutput('contents')
)
))
# Server component
server <- function(input, output, session){
output$contents <- renderTable({
req(input$file1)
inFile <- input$file1
read_excel(inFile$datapath, 1)
req(input$file2)
inFile <- input$file2
read_excel(inFile$datapath, 1)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
可以看到,它只显示一个文件。
有什么办法可以看到两个文件的头部吗?
问题是您的
renderTable
仅返回或呈现第二个read_excel
读取的第二个表。如果你想呈现多个表,你必须将它们绑定到一个或使用多个renderTable
s,就像我在下面的代码中所做的那样,这可以很容易地推广到两个以上的表:
library(shiny)
library(readxl)
writexl::write_xlsx(mtcars, "mtcars.xlsx")
writexl::write_xlsx(iris, "iris.xlsx")
ui <- fluidPage(
titlePanel("Upload Excel file"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose first file",
accept = c(".xlsx"),
buttonLabel = "Upload",
multiple = TRUE
),
fileInput("file2", "Choose second file",
accept = c(".xlsx"),
buttonLabel = "Upload",
multiple = TRUE
)
),
mainPanel(
uiOutput("tables")
)
)
)
datasets <- list(mtcars, iris)
server <- function(input, output, session) {
output$tables <- renderUI({
table_output_list <- lapply(1:2, function(i) {
table_name <- paste0("table", i)
tableOutput(table_name)
})
do.call(tagList, table_output_list)
})
lapply(1:2, function(i) {
table_name <- paste0("table", i)
output[[table_name]] <- renderTable({
req(input[[paste0("file", i)]])
inFile <- input[[paste0("file", i)]]
head(read_excel(inFile$datapath, 1))
})
})
}
shinyApp(ui = ui, server = server)