闪亮:使用rhandsontable在响应式数据集之间切换

5
在下面的玩具示例中,我有两个数据集df1和df2。使用shiny和rhandsontable将这些数据集输出到交互式表格中。我的问题是,当用户没有编辑在shiny应用程序中的数据集时(如is.null(input$out)所示),output$out仅识别数据集的偏移量。
当input$out不为空时,如何修复以下代码以加载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)
1个回答

8
您可以使用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会被更新。在观察器中,input$df是被隔离的,这样代码的这部分仅对用户更改表格时作出反应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接