所选的本地文件未显示具有不同条件的Shiny应用

时间:2018-12-14 19:39:12

标签: r shiny

我尝试过在网上大量搜索类似的问题,但找不到适合我的情况的问题。我对Shiny陌生,所以希望大家能帮助我。下面是我所拥有的一种代码形式。

OverflowError

在用户界面中,您可以在下拉菜单中看到我可以选择多个县并将其合并的原因。在我的文件夹中,有许多以这种通用格式命名的png文件:“ CountyX reasonY .png”(文件扩展名前有一个空格)。

在我的实际情况下,我知道我的计算机上有以下文件:

  • 县1原因1
  • County1原因2
  • County1原因3
  • County1原因4
  • County2原因1
  • County2原因4

但是在Shiny中,当我选择显示County1&2并勾选原因1&4时,我只会看到

  • County1原因1
  • County2原因4

代替

  • County1原因1
  • County1原因4
  • County2原因1
  • County2原因4

即使我知道这些文件确实存在(如上所述)。

我已经上传了一些文件进行实验:County1 reason1County1 reason2County1 reason3County1 reason4County2 reason1County2 reason4

这是我所能描述的最好的问题。希望能对您有所帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

编写Shiny应用程序时,最好遵循反应式编程原则(经常使用reactives(),但这不是唯一的要求),并用req()对输入进行清理(请参阅{{ 3}})。

您关于在文件名中包含特定组合的问题与R而不是Shiny有关。将paste()lapply()配合使用足以满足您的需求。另一方面,根据经验,请勿在文件名中留空格,必要时不要使用连字符或下划线。

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  titlePanel("Compare"),
  sidebarLayout(
    sidebarPanel(
      pickerInput(inputId = "countyInput", label = "Filter county",
                  choices = c("County1", "County2", "County3", "County4", "County5"),
                  options = list(`actions-box` = TRUE,size = 10, `selected-text-format` = "count > 9"),
                  multiple = TRUE),
      checkboxGroupInput(inputId = "reasonInput", label = "Filter reason",
                         choices = c("Reason1", "Reason2", "Reason3"))
    ),
    mainPanel(
      uiOutput("images")
    )
  )
)

server <- function(input, output, session) {

  file_name <- reactive({
    req(input$countyInput)
    req(input$reasonInput)
    paste0(unlist(lapply(input$countyInput, function(i) {
      paste0(i, input$reasonInput)
    })), ".png")
  })

 # creating multiple outputs:
  output$images <- renderUI({
    tagList(
      lapply(file_name(), function(file) {
        output[[paste("img", file, sep = "_")]] <- renderImage({

          filename <- file.path(Sys.getenv("HOME"), file)
          # validation intermed objects and msg displayed in UI:
          shiny::validate(
            shiny::need(file.exists(filename), "File not found.")
          )

          list(src = filename,
               alt = paste("Image name", file))
        }, deleteFile = FALSE) # we don't want Shiny to delete our file after read.
      })
    )
  })
}

shinyApp(ui, server)