【问题标题】:Shiny: Switching between reactive data sets with rhandsontableShiny:使用 rhandsontable 在反应式数据集之间切换
【发布时间】:2015-11-24 09:13:18
【问题描述】:

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

当 input$out 不为 null 时 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)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以使用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 是隔离的,因此这部分代码仅在用户更改表时才做出反应。

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 2018-10-03
      • 1970-01-01
      • 2016-11-30
      • 2017-10-19
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2016-11-14
      相关资源
      最近更新 更多