Shiny - 编辑具有多个输入和输出元素的 rhandsontable 表

Shiny - Editing rhandsontable tables with multiple input and output elements

我一直以此 post 作为起点。

非常有帮助,但我正在尝试扩展它以指定 table 中值的数量,然后在编辑后根据 table 值更新绘图。

这是我目前的情况。

library(shiny)
library(rhandsontable)
library(colorSpec)

ui <- fluidPage(
  numericInput("x", "number of values", 2),
  rHandsontableOutput('table'),
  textOutput('result'),
  plotOutput('plot'),
  actionButton("recalc", "generate new random vals and calculate")
)


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

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

  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)
  })

  output$plot <- reactivePlot({
    barplot(values$data)
  })

})

shinyApp(ui = ui, server = server)

我在 reactiveValues 行遇到错误,因为我正在尝试使用 input$x。之前的 post 的硬编码值为 2。

您可以使用 reactive() 而不是 reactiveValues 来执行此操作:

library(shiny)
library(rhandsontable)
library(colorSpec)

ui <- fluidPage(
  numericInput("x", "number of values", 2),
  rHandsontableOutput('table'),
  textOutput('result')
)


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

  values <- reactive({
    foo <- as.data.frame(runif(input$x))
    colnames(foo) <- c("Col1")
    return(foo)
  })

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


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

})

shinyApp(ui = ui, server = server)

我想你快到了。但是,您不能使用输入来创建反应值。但这无论如何都没有结束,你可以用 NULL 来启动它。

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  numericInput("x", "number of values", 2),
  rHandsontableOutput('table'),
  textOutput('result'),
  plotOutput('plot'),
  actionButton("recalc", "generate new random vals and calculate")
)


server <- function(input,output,session)({
  values <- reactiveValues(data = NULL) ## assign it with NULL

  ## button press resets now the data frame
  observeEvent(input$recalc, { 
    values$data$x <- 0
  })

  ## changes in numericInput sets all (!) new values
  observe({
    req(input$x)
    values$data <- data.frame(x = runif(input$x))
  })

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


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


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

  output$plot <- renderPlot({
    req(values$data)
    barplot(values$data$x)
  })

})

shinyApp(ui = ui, server = server)