【发布时间】:2020-01-07 21:16:51
【问题描述】:
我有一个迷你 Shiny 应用程序,它可以按需要运行。 首先,在应用程序的文件夹中,我为两个商店生成了一个包含数据框的列表:
stores <- list(store1 = tibble(Date = as.Date(c("2019-08-31", "2019-09-01", NA)), Item = c("A", "B", NA),
Price = c(100, 120, NA), Comment = as.character(rep(NA, 3))),
store2 = tibble(Date = as.Date(c("2019-08-31", NA, NA)), Item = c("C", NA, NA),
Price = c(95, NA, NA), Comment = as.character(rep(NA, 3))))
saveRDS(stores, file = "stores.rds")
print(stores)
这是我的闪亮代码。我希望用户能够根据需要更新每个商店表中的信息,并通过单击“更新商店信息”操作按钮保存更改。
但是,请注意:在服务器代码的末尾我有这个“条件”行: mutate(Comment = ifelse(Price > 100, "Nice!", Comment)): If Price is > 100, a comment "好的!”应该会出现 - 无需我手动输入。
问题:我不知道如何在单击 input$update_store 时使此条件注释出现在屏幕上的表格中。我可以在下拉菜单中切换到另一家商店,然后回到第一家商店 - 评论就会出现!但是有没有办法让它在点击 input$update_store 后立即更新?
非常感谢您的帮助!
library(shiny)
library(dplyr)
library(rhandsontable)
# Read in the existing list of stores:
stores <- readRDS("stores.rds")
print("Reading in stores the first time:")
print(stores)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### ui code ####
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ui <- fluidPage(
titlePanel("My UI"), # Application title
sidebarLayout( # Sidebar with a pull-down to select a store:
sidebarPanel(
selectizeInput("store_select", label = "Select store",
choices = names(stores), multiple = FALSE,
selected = names(stores)[1]),
actionButton("update_store", "Update store Info")
),
mainPanel( # Main panel with an editable table:
rHandsontableOutput("store_table")
)
)
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### server code ####
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
server <- function(input, output, session) {
stores_reactive <- reactiveValues( # Creating reactive values for stores:
stores = stores
)
# What happens when one store is selected:
mystore <- eventReactive(input$store_select, {
store_name <- input$store_select
store_table <- stores_reactive$stores[[store_name]]
return(store_table)
})
# rhandsontable to be shown:
output$store_table <- renderRHandsontable({
rhandsontable(mystore())
})
# What happens upon pressing button "Update store Info":
observeEvent(input$update_store, {
stores[[input$store_select]] <- hot_to_r(input$store_table) %>%
mutate(Comment = ifelse(Price > 100, "Nice!", Comment))
stores_reactive$stores <- stores # Update stores_reactive
saveRDS(stores, file = "stores.rds") # save stores to the file
stores <<- stores # Update 'stores' list
})
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### Run the app ####
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
shinyApp(ui = ui, server = server)
【问题讨论】:
标签: r shiny reactive rhandsontable