【问题标题】:Restart shiny app from within app (reloading data)从应用程序内重新启动闪亮的应用程序(重新加载数据)
【发布时间】:2017-08-10 22:16:12
【问题描述】:

我想从应用程序中重新启动闪亮的应用程序,例如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)

【问题讨论】:

  • 能否提供样本数据?
  • 不是您问题的答案,但您可能喜欢github.com/r-spatial/mapedit 作为实现相同目标的一种方式。

标签: r shiny shinyjs


【解决方案1】:

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

【讨论】:

  • 拯救了我的一天!!经过数小时的重构。我遇到了这个过时的数据问题。
  • 我将数据加载代码放在服务器之外,必须启动一个新应用程序才能获取应用程序使用的更新数据。非常感谢@SBista
猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2018-10-14
  • 2018-06-13
  • 2013-01-31
  • 1970-01-01
  • 2019-07-25
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多