我试图创建一个带有fileInput
的Shiny应用程序,该应用程序包含多个文件,但后来我确认输入了预期的文件(这是因为有太多要单独生成{ {1}}每个人)。对应的fileInput
执行验证。我没有列出所有必需的文件,而是列出了所有必需的文件。我创建了一个快速示例应用程序,以显示我正在寻找的内容
reactive
魔法在library(shiny)
fileList <- c("fileA.txt", "fileB.txt")
ui <- fluidPage(
titlePanel("Text Concatanation"),
sidebarLayout(
sidebarPanel(
fileInput("theFiles", "Load files:", multiple = TRUE)
),
mainPanel(
verbatimTextOutput("textConcat")
)
)
)
server <- function(input, output, session) {
theText <- reactive({
missingFiles <- fileList
validate(
need({
# missingFiles <- setdiff(fileList, input$theFiles$name) # works but error message doesn't change
missingFiles <<- setdiff(fileList, input$theFiles$name) # does not work and causes the test to fail
length(missingFiles) == 0
},
paste("Missing required files:", paste(missingFiles, collapse = ",")))
)
x <- lapply(input$theFiles$datapath, readLines)
names(x) <- input$theFiles$name
x
})
output$textConcat <- renderText({
print(x)
x <- lapply(theText(), paste, collapse = "\n")
x <- mapply(paste, names(x), x, sep = ":\n\n")
x <- paste(x, collapse = "\n\n\n")
x
})
}
shinyApp(ui, server)
reactive
中执行。我想要的是,如果我加载theText
但不加fileA.txt
,我会收到fileB.txt
之类的错误消息。我想使用Missing required files: fileB.txt
赋值运算符来转义<<-
里面的表达式的上下文会做的伎俩,但不仅仅是它无法修改need
,即使我的测试也失败了加载missingFiles
和fileA.txt
。是否有fileB.txt
在此用法中失败的原因?
答案 0 :(得分:0)
这里的问题是你试图在函数need
的第一个参数内生成丢失的文件。我建议的是将这个逻辑移到外面并保持need
整洁。如下所示:
library(shiny)
ui <- fluidPage(
titlePanel("Text Concatanation"),
sidebarLayout(
sidebarPanel(
fileInput("theFiles", "Load files:", multiple = TRUE)
),
mainPanel(
verbatimTextOutput("textConcat")
)
)
)
server <- function(input, output, session) {
fileList <- c("fileA.txt", "fileB.txt") # files that are required
# files that are currently missing
missingFiles <- reactive({
fileList[!fileList %in% input$theFiles$name]
})
output$textConcat <- renderPrint({
validate(
need(
length(missingFiles()) == 0,
paste0("Missing files: ", paste(missingFiles(), collapse = ", "))
)
)
"nice, all files are uploaded"
})
}
shinyApp(ui, server)