闪亮:使用rhandsontable在反应性数据集之间切换 [英] Shiny: Switching between reactive data sets with rhandsontable

查看:20
本文介绍了闪亮:使用rhandsontable在反应性数据集之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的玩具示例中,我有两个数据集df1和df2。使用SHINY&;rhandsontable将数据集输出到交互式表格。我的问题是,如果用户没有按照is.null(input$out)指示的那样在闪亮的应用程序中编辑数据集,则输出$out只识别数据集中的移位。

如何修复以下代码,以便在输入$OUT不为空的情况下更改输入$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。在观察器中,input$df是独立的,因此这部分代码仅在用户更改表时做出反应。

这篇关于闪亮:使用rhandsontable在反应性数据集之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆