实现这样的事情的一种方法(如果我理解正确的话)是使用radioButtons 让用户选择输入类型。然后根据用户的选择呈现不同的输入元素,并有一个响应式来适当地处理两种不同的输入文件类型。最后,我们从 excel 或 googlesheets 文件呈现单个表格。
代码:
library(shiny)
library(tidyverse)
# let the user choose the type of input file
radioButtons(
inputId = "what_source",
label = "Choose source file",
choices = c("googlesheets", "excel"),
inline = FALSE
)
# render file input widgets conditioned on user choice
conditionalPanel(condition = 'input.what_source == "googlesheets"',
fileInput("google_file", "Upload from csv", accept = ".csv")
)
conditionalPanel(condition = 'input.what_source == "excel"',
fileInput("excel_file", "Upload from excel", accept = ".xlsx")
)
# deal with the file selected by the user
what_file <- reactive({
if (input$what_source == "googlesheets") {
x <- readr::read_csv(input$google_file$datapath) %>% mutate(source = "csv")
} else {
x <- readxl::read_excel(input$excel_file$datapath) %>% mutate(source = "Excel")
return(x)
}
})
# then in a different element downstream add the render function:
renderDataTable(what_file())
更新:随意取csv,但用checkbox改成excel输入:
服务器逻辑:
# fetch updated csv data
actionButton("fetch", "Fetch new data")
checkboxInput("excel", label = "Get excel file", value = FALSE)
fetch_new <- eventReactive(input$fetch, {
readr::read_csv("df.csv")
})
conditionalPanel(condition = 'input.excel == true',
fileInput("excel_file",
"Upload from excel",
accept = ".xlsx")
)
what_file <- reactive({
if (!input$excel) {
x <- fetch_new()
} else {
x <- readxl::read_excel(input$excel_file$datapath)
return(x)
}
})