【问题标题】:How to conditionally set a reactive value with fileInput?如何使用 fileInput 有条件地设置反应值?
【发布时间】:2021-07-11 00:53:32
【问题描述】:

我正在尝试上传 csv 文件或 rds 文件,并将其用作创建表的数据集。我尝试使用条件if/else,但出现此错误:argument is of length zero。我想将它上传到渲染表之外,因为我也想将反应数据集用于其他目的。

代码


library(shiny)

ui <- fluidPage(

    sidebarLayout(
        sidebarPanel(
            fileInput("file_csv", "Choose CSV File", accept = ".csv"),
            checkboxInput("header", "Header", TRUE),
            fileInput("file_rds", "Choose RDS File", accept = ".rds"),
        ),

        mainPanel(
           tableOutput("table1")
        )
    )
)

server <- function(input, output) {

    dataset <- reactive({
        if(input$file_csv) {
            file <- input$file_csv
            ext <- tools::file_ext(file$datapath)
            
            req(file)
            validate(need(ext == "csv", "Please upload a csv file"))
            
            read.csv(file$datapath, header = input$header)
        } else {
            readRDS(file_rds$datapath)
        }
    })
    
    output$table1 <- renderTable({
        head(dataset())
    })
}

shinyApp(ui = ui, server = server)

尝试使用observeEvent(不起作用):


    output$table1 <- renderTable({
        req(dataset())
        head(dataset())
    })
    
    observeEvent(input$file_csv, {
        dataset <- read.csv(input$file_csv$datapath, header = input$header)
    })
 
    observeEvent(input$file_rds, {
        dataset <- readRDS(input$file_rds$datapath)
    })
      

尝试 rds 文件(不工作):

       if(!is.null(input$file_rds )) {
            
            file <- input$file_rds
            req(file)
            
            readRDS(file$datapath)
            
            }

【问题讨论】:

  • if(input$file_csv) 在这里不是逻辑条件,因为input$file_csv 可以为空或字符串值
  • 我通常用req(input$file_csv) 开始这样的反应,因为它可以排除大多数这样的问题。
  • 我尝试添加req(input$file_csv),但它没有解决 akrun 指出的逻辑问题。在这种情况下,什么是好的逻辑条件?
  • 我猜你可能需要is.nullwrapped
  • 我尝试了另一种方法,但没有奏效。请查看更新。

标签: r shiny


【解决方案1】:

我们可以使用

server <- function(input, output) {
  
  dataset <- reactive({
    req(input$file_csv)
    if(!is.null(input$file_csv )) {
      file <- input$file_csv
      ext <- tools::file_ext(file$datapath)
      
      req(file)
      validate(need(ext == "csv", "Please upload a csv file"))
      
      read.csv(file$datapath, header = input$header)
    } else {
      readRDS(input$file_rds$datapath)
    }
  })
  
  output$table1 <- renderTable({
    head(dataset())
  })
}
  • 输出

-验证检查

【讨论】:

  • 我无法让 rds 文件正常工作。它对你有用吗?
  • 我没有要检查的 RDS 文件
  • 我试过这个:saveRDS(mtcars, file = "mtcars.rds")
  • @TyperWriter 我认为它必须与更新 selectInput 有关。如果你做相反的事情,它适用于 readRDS 即if(!is.null(input$file_rds ))
  • @TyperWriter 你检查过你自己问题中的解决方案吗here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2018-04-02
  • 1970-01-01
  • 2010-09-08
  • 2023-02-08
  • 1970-01-01
  • 2012-08-02
相关资源
最近更新 更多