我想从应用内重新启动一个闪亮的应用,以便例如global.R中的代码将再次执行(用数据重新加载csv文件)。这是一个显示我想要做的最小例子:
这个闪亮的应用程序加载一些坐标数据并绘制地图上的标记。将新标记添加到地图时,新坐标应附加到旧数据并保存为csv文件。然后应用程序应重新启动,再次加载data.csv,以便所有标记都显示在地图上。我尝试从这里调整代码:Restart Shiny Session但这不起作用。应用程序重新启动,但不会重新加载csv文件。
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)
答案 0 :(得分:4)
要重新加载csv文件,您需要在服务器内部读取文件。
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
})
}