r - Shiny:使用 rhandsontable 在响应式(Reactive)数据集之间切换

标签 r shiny

在下面的玩具示例中,我有两个数据集 df1 和 df2。使用shiny & rhandsontable 将数据集输出到交互式表格。我的问题是,如果用户没有像 is.null(input$out) 所指示的那样编辑 Shiny 的应用程序中的数据集,则 output$out 仅识别数据集的变化。

当 input$out 不为空时 input$df 更改时,如何修复以下代码以加载 df1 或 df2?

require(rhandsontable)
require(shiny)

df1 <- data.frame(col1 = rnorm(20),
                  col2 = rep(T, 20))

df2 <- data.frame(col1 = rnorm(20),
                  col2 = rep(F, 20))

funcX <- function(x) {
  x$out <- ifelse(x$col2 == T, x$col1 * 1.5, x$col1)
  x$out
}

df2$out <- funcX(df2)
df1$out <- funcX(df1)

server <- function(input, output) {

  df <- reactive({
    if (input$df == "df1") {
      df <- df1
    } else {
      df <- df2
    }
    df
  })

  output$out <- renderRHandsontable({
    if (is.null(input$out)) {
      hot <- rhandsontable(df())
    } else {
      str(input$out)
      hot <- hot_to_r(input$out)
      hot$out <- funcX(hot)
      hot <- rhandsontable(hot)
    }
    hot
  })
}

ui <- fluidPage(sidebarLayout(sidebarPanel(
  selectInput(
    'df', 'Select data.frame:',
    choices = c('df1', 'df2'),
    selected = 'df1'
  )
),
mainPanel(rHandsontableOutput("out"))))

shinyApp(ui = ui, server = server)

最佳答案

您可以使用 reactiveValues存储 df1df2数据框,并在修改这些值时更新这些值。这是一个例子 server.R代码:

server <- function(input, output) {

  values = reactiveValues()
  values[["df1"]] <- df1
  values[["df2"]] <- df2

  observe({   
    if (!is.null(input$out)) {  
      temp <- hot_to_r(input$out)
      temp$out <- funcX(temp)
      if (isolate(input$df) == "df1") {       
        values[["df1"]] <- temp
      } else {
        values[["df2"]] <- temp
      }
    }
  })

  df <- reactive({
    if (input$df == "df1") {
      df <- values[["df1"]]
    } else {
      df <- values[["df2"]]
    }
    df
  })

  output$out <- renderRHandsontable({
    hot <- rhandsontable(df())
    hot
  })
}

换表时,正确df1df2在 react 值中更新。在观察者中,input$df是隔离的,因此这部分代码仅在用户更改表时使用react。

关于r - Shiny:使用 rhandsontable 在响应式(Reactive)数据集之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32292547/

相关文章:

r - Slurm群集中的R代码无法正确读取

r - 将 Quantstrat 中的时间范围从每日更改为每周

r - 填充 R 中缺失的 GPS 值

javascript - 在 Shiny 的 textOutput() 更改后触发 react

r - 分解 R 包中的 disag_model() 函数存在问题

r - 作为独立程序 Shiny

r - 如何在 Shiny 的 sliderInput() 中添加加号和减号箭头?

rglwidget : Cannot replace previous 3d plot

r - 更改操作按钮的颜色

r - 如何计算R中的月差