有没有办法用 fileInput 覆盖 Rshiny 中的反应值

Is there a way to override a reactive value in Rshiny with a fileInput

我正在尝试允许用户 (a) 上传文件(在本例中为 mtcars)或 (b) 按下一个按钮并检索文件,但有一个条件(在本例中为 mtcars$gears = 0)。用户可以上传文件。美好的。用户可以 select 按钮。美好的。但是当用户 select 按下按钮,然后上传文件时,它并没有上传文件。它保持条件 mtcars$gears = 0.

library(dplyr)
library(shiny)

ui <- fluidPage(sidebarLayout(
  sidebarPanel(
    fileInput("file1", "Choose CSV File", accept = ".csv"),
    checkboxInput("header", "Header", TRUE),
    br(),
    actionButton("button1", "Populate all gear with 0s")
  ),
  mainPanel(tableOutput("contents"))
))

server <- function(input, output) {
  rv = reactiveValues()
  
  rv$table1 <- reactive({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
    
    req(file)
    #validate(need(ext == "csv", "Please upload a csv file"))
    
    read.csv(file$datapath, header = input$header)
  })
  
  
  observeEvent(input$button1, {
    rv$table1 = reactive(mtcars %>% mutate(gear = 0))
  })
  
  output$contents <- renderTable({
    rv$table1()
  })
  
}

shinyApp(ui, server)


对您的服务器代码进行微调应该可以解决这个问题。

server <- function(input, output) {
  rv = reactiveValues()
  
  mydf <- reactive({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)
    
    req(file)
    #validate(need(ext == "csv", "Please upload a csv file"))
    
    read.csv(file$datapath, header = input$header)
  })
  
  observeEvent(input$file1, {
    rv$table1 = mydf()
  })
  
  observeEvent(input$button1, {
    rv$table1 = mtcars %>% mutate(gear = 0)
  })
  
  output$contents <- renderTable({
    rv$table1
  })
  
}