在Shiny中初始化和更新被动(data.table)?

时间:2018-02-22 14:17:52

标签: r shiny data.table

是否有可能将闪光中的反应性初始化? 我想要一个有反应性的data.table。这个data.table的一部分不会改变,因此我不需要在每次输入更改时重新初始化它,而只需要更新列" original_values"和" working_values"。

这可能吗?或者这是case for better using reactiveValues() with observe(),即使我是calculate values here and do not have sideeffects

library(shiny)
library(data.table)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider1", "Slider 1",min = 0.1, max = 1, value = 0.4, step = 0.05),
      sliderInput("slider2", "Slider 2",min = 0.1, max = 1, value = 0.4, step = 0.05),                               
      sliderInput("slider3", "Slider 3",min = 100, max = 20000, value = 5000, step= 200)
    ), 
    mainPanel(
      tableOutput("tableOut")

    )

  ))

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

      #initalization - can this be put somewhere else?
      ret <- data.table(slider_names= c("slider1","slider2", "slider3"), 
                        some_grouping_information=c("A", "A", "B") )

      #actual reactive
      ret[,original_values :=c(input$slider1,input$slider2,input$slider3)]
      ret[,working_values:=sum(original_values), by=some_grouping_information]

    })

    output$tableOut<- renderTable(rv_dtWeights())

  }
  shinyApp(ui = ui, server=server)

1 个答案:

答案 0 :(得分:3)

您可以将其放在reactive以外的server(或server之外),以获取有关差异的更多信息,请参阅here )。下面给出了一个示例,其中data.table仅在用户打开应用程序时初始化一次。

希望这有帮助!

library(shiny)
library(data.table)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      sliderInput("slider1", "Slider 1",min = 0.1, max = 1, value = 0.4, step = 0.05),
      sliderInput("slider2", "Slider 2",min = 0.1, max = 1, value = 0.4, step = 0.05),                               
      sliderInput("slider3", "Slider 3",min = 100, max = 20000, value = 5000, step= 200)
    ), 
    mainPanel(
      tableOutput("tableOut")

    )

  ))

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

  #initalization - can this be put somewhere else?
  ret <- data.table(slider_names= c("slider1","slider2", "slider3"), 
                    some_grouping_information=c("A", "A", "B") )


  rv_dtWeights <- reactive({
    #actual reactive
    ret[,original_values :=c(input$slider1,input$slider2,input$slider3)]
    ret[,working_values:=sum(original_values), by=some_grouping_information]

  })

  output$tableOut<- renderTable(rv_dtWeights())

}
shinyApp(ui = ui, server=server)