shiny正则表达式 爬虫R语言问题集锦

「R shiny 抓虫」为什么我的fileInput失效了?

2019-03-27  本文已影响31人  xuzhougeng

只有经历几个我得花好久才能找到的bug,我才觉得我有点会用Shiny了

今天在写Shiny 的时候遇到了几个巨大的问题,就是Shiny中一个组件fileInput无论如何都无法上传文件

fileinput

我在这个问题上花了差不多1个小时时间,其中大概做了如下几件事情:

直到问题的解决的一瞬间,我才认识到福尔摩斯的话是多么正确

当你排除所有的不可能,无论剩下的是什么,即使是不可能也一定是真相.

接下来,我就提供一个最简单的代码复现出我的问题。由于这是很最简洁代码了,相信大家应该能够比较容易发现错误

if (interactive()) {
  
  ui <- fluidPage(
    sidebarLayout(
      sidebarPanel(
        fileInput("file1", "Choose CSV File",
                  accept = c(
                    "text/plain",
                    ".vcf")
        ),
        tags$hr(),
        checkboxInput("header", "Header", TRUE)
      ),
      mainPanel(
        tableOutput("contents"),
        downloadLink("a",label = "Download"),
        downloadLink("a",label = "Download")
      )
    )
  )
  
  server <- function(input, output) {
  output$contents <- renderTable({
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, it will be a data frame with 'name',
    # 'size', 'type', and 'datapath' columns. The 'datapath'
    # column will contain the local filenames where the data can
    # be found.
    inFile <- input$file1

    if (is.null(inFile))
      return(NULL)

    read.csv(inFile$datapath, header = input$header)
  })

}
  
  shinyApp(ui, server)
}

我用动图演示下效果

错误演示

下面是正确答案的分割线


文件无法上传的原因是下面这两行一模一样的代码。由于他们拥有相同的outputId, 其结果就是Shiny 没有解析出数据的输入和数据,结果导致Shiny的reactive体系无法正确调用server函数

        downloadLink("a",label = "Download"),
        downloadLink("a",label = "Download")

有了这个血泪教训,我想之后,我应该更会小心的处理inputIdoutputId了吧

我的一个好朋友果子老师经常说我成长很快,因为他们做一次实验的时间,我们的运算可以重复很多次。但是同样的,我们明天也要经历更多的失望。那些杀不死你的会让你更强大,所以我变秃了,也变强了。

上一篇 下一篇

猜你喜欢

热点阅读