【问题标题】:How to change a value in a reactive tibble in R Shiny如何在 R Shiny 中更改反应小标题中的值
【发布时间】:2020-02-25 21:23:40
【问题描述】:

我想更新一个响应式对象的内容,该对象持有一个小标题以响应按钮按下,但我不知道语法。 here 发布的解决方案包含一个过去可以工作但现在引发错误的解决方案。

以下是我遇到的问题的代表。先运行write.csv(iris, "text.csv")

library(shiny)
library(tidyverse)

# create the test data first
# write.csv(iris, "text.csv")

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

    in_data <- reactive({
        inFile <- input$raw
        x <- read.csv(inFile$datapath, header=TRUE)
    })

    subset <- reactive({
        subset <- in_data() %>%
            filter(Species == "setosa")
    })

    observeEvent(input$pushme, {
            subset()$Sepal.Length[2] <- 2
    })

    output$theOutput <- renderTable({
        subset()
    })
})


ui <- shinyUI(
    fluidPage(
        fileInput('raw', 'Load test.csv'),
        actionButton("pushme","Push Me"),
        tableOutput('theOutput')     
    )
)
shinyApp(ui,server)

我的更改值的代码:

subset()$Sepal.Length[2] <- 2

抛出此错误:

Error in <-: invalid (NULL) left side of assignment

以编程方式更改响应式小标题中的值的语法是什么?

【问题讨论】:

    标签: r shiny reactive


    【解决方案1】:

    您不能直接修改反应对象的值。您必须首先定义一个静态对象,该对象将获取反应对象的值,然后您可以修改静态对象的值。两个选项供您选择(ui 中没有修改):

    • 第一个是在对数据进行子集化后使用renderTable,然后在observeEvent 中修改您的表:
    server <- shinyServer(function(input, output) {
    
      in_data <- reactive({
        inFile <- input$raw
        x <- read.csv(inFile$datapath, header=TRUE)
      })
    
      test1 <- reactive({
        data <- in_data() %>%
          filter(Species == "setosa")
        data
      })
    
      output$theOutput <- renderTable({
        req(input$raw)
        test1()
      })
    
      observeEvent(input$pushme, {
        output$theOutput <- renderTable({
          req(input$raw)
          test1 <- test1()
          test1$Sepal.Length[2] <- 2
          test1
        })
      })
    
    })
    
    • 第二个是定义另一个数据集(此处为test2),仅当按下按钮时才会使用eventReactive 进行计算。然后,您必须使用它们存在的条件来定义要在 renderTable 中使用的两个数据集中的哪一个:
    server <- shinyServer(function(input, output) {
    
      in_data <- reactive({
        inFile <- input$raw
        x <- read.csv(inFile$datapath, header=TRUE)
      })
    
      test1 <- reactive({
        data <- in_data() %>%
          filter(Species == "setosa")
        data
      })
    
      test2 <- eventReactive(input$pushme, {
          test1 <- test1()
          test1$Sepal.Length[2] <- 2
          test1
        }
      )
    
      output$theOutput <- renderTable({
        if (input$pushme) {
          test2()
        }
        else {
          req(input$raw)
          test1()
        }
      })
    
    })
    

    顺便说一句,您不应该像函数名称那样调用数据集(反应性或非反应性)。在您的示例中,您调用了 subset 您修改的反应数据集。这不好,因为该数据集将用作subset()(因为它是反应性的)。这可能会让您和代码的执行感到困惑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      相关资源
      最近更新 更多