问题
I want to restart a shiny app from within the app, so that e.g. code in global.R will be executed again (to reload a csv file with data). Here is a minimal example showing what I want to do:
This shiny app loads some coordinates data and plots markers on a map. When a new marker is added to the map, the new coordinates should be appended to the old data and saved as a csv file. Then the app should restart, load data.csv again, so all markers are shown on the map. I tried adapting code from here: Restart Shiny Session but this doesn't work. The app restarts, but it doesn't reload the csv file.
library(shinyjs)
library(leaflet)
library(leaflet.extras)
jsResetCode <- "shinyjs.reset = function() {history.go(0)}"
# data <- data.frame(latitude = 49, longitude = 13)
data <- read.csv2("data.csv") # this should get executed whenever js$reset is called
ui <- fluidPage(
useShinyjs(),
extendShinyjs(text = jsResetCode),
leafletOutput("map")
)
server <- function(input, output, session){
output$map <- renderLeaflet({
leaflet(data) %>% addTiles() %>%
setView(11.5, 48, 7) %>%
addDrawToolbar() %>%
addMarkers()
})
data_reactive <- reactiveValues(new_data = data)
# add new point to existing data and save data as data.csv
# after that the app should restart
observeEvent(input$map_draw_new_feature, {
data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
js$reset() # this should restart the app
})
}
shinyApp(ui, server)
回答1:
To reload the csv file you need to place reading of the file inside the server.
server <- function(input, output, session){
#Read the data inside the server!!!
data <- read.csv2("data.csv")# this should get executed whenever js$reset is called
output$map <- renderLeaflet({
leaflet(data) %>% addTiles() %>%
setView(11.5, 48, 7) %>%
addDrawToolbar() %>%
addMarkers()
})
data_reactive <- reactiveValues(new_data = data)
# add new point to existing data and save data as data.csv
# after that the app should restart
observeEvent(input$map_draw_new_feature, {
# browser()
data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
js$reset() # this should restart the app
})
}
来源:https://stackoverflow.com/questions/42889993/restart-shiny-app-from-within-app-reloading-data