如何在 R Shiny Flexdashboard 中覆盖(单击操作按钮时)响应式对象



我试图制作一个R Shiny Flexdashboard,允许用户利用本地Excel文件下载的Googlesheet作为数据源。

我在这里创建了一个示例,但我使用了一个本地 csv 文件来代替 Googlesheets 下载组件(在示例中使用 googlesheets 会很复杂(。

https://gist.github.com/jtag04/67ae6b2c39e4f68f90e06bb1ce2ceb98

上面的脚本有效(将其另存为 *.rmd 文件以便运行 - 它是一个 Flexdashboard(。

但是,我的挑战是我希望 *csv 上传(按下 actionButton 时(覆盖 Excel 文件对象(如果存在(。

即,不是将 CSV 保存到step_one_2(如示例中所示(,以便它覆盖step_one对象(如果存在(。

这可能吗? 提前非常感谢。

实现这样的事情的一种方法(如果我正确理解了所有内容(是使用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,但更改为带有复选框的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)
}
})

最新更新