gpt4 book ai didi

r - 通过编辑 table 和/或 eventReactive 更新 handsontable

转载 作者:行者123 更新时间:2023-12-04 03:19:51 26 4
gpt4 key购买 nike

我正在使用 rhandsontable打包在一个 Shiny 应用程序中,它应该具有以下功能:

  • 计算中使用的数据可以随机生成,由actionButton调用(以及应用程序启动时)
  • 用户可以通过handsontable对象手动编辑数据
  • 手动编辑后应该可以重新生成随机数据,调用新的计算

  • 下面的应用程序正是我想要的,但我不知道如何摆脱全局变量 did_recalc .这是一个最小的例子,其中数据由两个相加的数值组成。
    library(shiny)
    library(rhandsontable)

    did_recalc <- FALSE

    ui <- fluidPage(
    rHandsontableOutput('table'),
    textOutput('result'),
    actionButton("recalc", "generate new random vals and calculate")
    )

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

    dataset_generator <- eventReactive(input$recalc, {
    df <- as.data.frame(runif(2))
    output$table <- renderRHandsontable({rhandsontable(df)})
    did_recalc <<- TRUE
    df
    }, ignoreNULL = FALSE)

    output$result <- renderText({
    df <- dataset_generator()
    if (!is.null(input$table) && !did_recalc)
    df <- hot_to_r(input$table)
    did_recalc <<- FALSE
    sum(df)
    })
    })

    shinyApp(ui = ui, server = server)

    如果我删除 !did_recalc条件在 output$result <- ...然后编辑表格仍然会调用(正确的)计算。但是如果按下“重新计算”(在完成一些手动编辑之后),那么“重新计算”按钮只会生成新的随机值,但不会重新计算总和。

    在我看来, input$table可以通过手动编辑表对象来更改,并且不关心通过 renderRHandsontable 给出的新值.因此,我需要对全局变量进行此 hack,这允许我跟踪用户是否刚刚重新生成数据(导致 input$table 已“过时”)

    有没有人知道如何在没有全局变量的情况下获得此示例的功能?

    最佳答案

    您可以将数据存储在 reactiveValues 中并让两个观察者更新它;一种是单击按钮,一种是手动编辑表格。

    在您的 output$tableoutput$result ,然后您只需要使用 reactiveValues 中的数据.这是一个示例(与您发布的 ui.R 相同):

    server <- function(input,output,session)({
    values <- reactiveValues(data=as.data.frame(runif(2)))

    observe({
    input$recalc
    values$data <- as.data.frame(runif(2))
    })

    observe({
    if(!is.null(input$table))
    values$data <- hot_to_r(input$table)
    })


    output$table <- renderRHandsontable({
    rhandsontable(values$data)
    })


    output$result <- renderText({
    sum(values$data)
    })
    })

    关于r - 通过编辑 table 和/或 eventReactive 更新 handsontable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33722757/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com