亲爱的 sackoverflow 的人们,
我目前正在尝试创建一个应用程序,用户可以在其中从各种来源上传数据集。我试图将上传代码隔离在一个单独的 Shiny 模块中。但是,R 会抛出一个错误,指出环境对象不是可子集的。我对 Shiny 还很陌生,所以我也会很感激关于模块使用的任何建议。:)
library(shiny)
fileInputUI <- function(id){
ns <- NS(id)
fileInput(
inputId = ns("file"),
label = "Select a file"
)
}
fileInputServer <- function(id){
moduleServer(id, function(input, output, session){
dataset <- reactive({
req(input$file)
# Get file extension and datapath
ext <- tools::file_ext(input$file$name)
datapath <- input$file$datapath
# Need reactive values to store input data in
read_data_options <- reactiveValues()
read_data_options$sep <- NULL
if(ext == "csv"){
choices_sep <- c(",", ";", "", "\\t")
names(choices_sep) <- c("Comma (,)", "Semicolon (;)", "White space ( )", "Tab separated (\\t)")
showModal(
ui = modalDialog(
selectInput(
inputId = NS(id, "sep"),
label = "Which separator is used for your data",
choices = names(choices_sep),
selected = ""
),
# Input is required so no dismiss button
footer = tagList(
modalButton("Dismiss"),
actionButton(
inputId = NS(id, "submit_csv"),
label = "Submit")
),
easyClose = TRUE
)
)
# Set input value from submit button
observeEvent(
eventExpr = input$submit_csv,
handlerExpr = {
read_data_options$sep <- choices_sep[input$sep]
removeModal()
read.csv(
file = datapath,
sep = read_data_options$sep
)
}
)
} else {
NULL
}
})
dataset
})
}
# Shiny App
ui <- fluidPage(
fileInputUI("test"),
tableOutput("head_data")
)
server <- function(input, output, session) {
dataset <- fileInputServer("test")
output$head_data <- renderTable(head(dataset()))
}
shinyApp(ui, server)
我使用了 modalDialog ,因为我认为它是向用户询问 read 函数的其他输入的最简单方法,例如 read.csv 的分隔符或 read.xlsx 的 startRow 等。
感谢您的回复