簡體   English   中英

如何在 R Shiny 應用程序中存儲反應變量的先前狀態?

[英]How to store previous states of reactive variables in R Shiny application?

讓我們想象一個 Shiny 應用程序,當用戶點擊一個 ActionButton 時,它會生成一個包含 10 個隨機單詞的向量。 這些單詞顯示在一個表格(DT 包)中,允許用戶 select 他感興趣的單詞/行以構建選擇。 此選擇被傳輸到另一個表(使用來自 DT 數據表的“_rows_selected”輸入)並顯示。 這就是下面的最小示例所做的:

library(shiny)
library(DT)

ui <- fluidPage(
  actionButton("generate", "New random words"),
  h5("Original data"),
  dataTableOutput("results"),
  br(),
  h5("Selected data"),
  dataTableOutput("selection")
)

server <- function(input, output, session) {
  
  generated_data <- eventReactive(input$generate, {
    random_words <- sapply(1:10, function(x) sample(letters, x) %>% paste(collapse=""))
    data.frame(ID=1:10, Word=random_words)
  })
  
  output$results <- renderDataTable(
    datatable(generated_data(), rownames = FALSE)
  )
  
  output$selection <- renderDataTable(
    generated_data()[input$results_rows_selected,] %>%
      datatable(rownames=FALSE)
  )
}

shinyApp(ui, server)

但是,如果用戶再次單擊操作按鈕,則會生成新單詞,因此會刪除第二個表中的選擇。 我希望選擇跟蹤以前選擇的單詞並添加我們選擇的任何新的單詞選擇。

我怎樣才能做到這一點? 如何在 memory 中保留我的反應變量的先前狀態(在通過新點擊生成新單詞時凍結)並將它們連接到當前選擇的單詞?

到目前為止我還沒有找到解決方案,在此先感謝您的幫助!

您可以將它們存儲在反應值中,如下所示:

all_words <- reactiveVal(data.frame(ID = integer(0), Word = character(0)))

generated_data <- eventReactive(input$generate, {
  random_words <- 
    sapply(1:10, function(x) sample(letters, x) %>% paste(collapse=""))
  dat <- data.frame(ID=1:10, Word=random_words)
  all_words(rbind(all_words(), dat))
  dat
})

通過稍微修改 Stéphane Laurent 提出的代碼,我可以提出這個完整的應用程序,該應用程序完全符合我的需求以及我提出問題時的想法。 可能有更簡潔的解決方案,特別是關於變量datall_words

library(shiny)
library(DT)

ui <- fluidPage(
  actionButton("generate", "New random words"),
  h5("Original data"),
  dataTableOutput("results"),
  br(),
  h5("Selected data"),
  dataTableOutput("selection")
)

server <- function(input, output, session) {
  
  all_words <- reactiveVal(data.frame(ID = integer(0), Word = character(0)))
  dat <- data.frame(ID=integer(0), Word=character(0))
  
  generated_data <- eventReactive(input$generate, {
    all_words(rbind(all_words(), dat[input$results_rows_selected,]))
    random_words <- 
      sapply(1:10, function(x) sample(letters, x) %>% paste(collapse=""))
    dat <<- data.frame(ID=1:10, Word=random_words)
    dat
  })
  
  output$results <- renderDataTable(
    datatable(generated_data(), rownames = FALSE)
  )
  
  output$selection <- renderDataTable(
    rbind(generated_data()[input$results_rows_selected,], all_words()) %>%
      datatable(rownames=FALSE)
  )
}

shinyApp(ui, server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM