gpt4 book ai didi

r - 从应用程序内部重新启动 Shiny 的应用程序(重新加载数据)

转载 作者:行者123 更新时间:2023-12-04 15:08:01 39 4
gpt4 key购买 nike

我想从应用程序内部重新启动 Shiny 的应用程序,例如global.R中的代码将再次执行(以将数据重新加载到csv文件中)。这是显示我想做什么的一个最小示例:

这个 Shiny 的应用程序会加载一些坐标数据并在 map 上绘制标记。将新标记添加到 map 后,新坐标应附加到旧数据中并另存为csv文件。然后,应用应重新启动,再次加载data.csv,以便所有标记都显示在 map 上。我尝试从此处改编代码: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)

最佳答案

要重新加载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
})
}

关于r - 从应用程序内部重新启动 Shiny 的应用程序(重新加载数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889993/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com