簡體   English   中英

模塊化R Shiny代碼:模塊中的ObserveEvent函數

[英]Modularizing R Shiny code: ObserveEvent function in module

我正在嘗試提高我的app.R代碼在R Shiny中的可用性,這已經變得很長了。

從本質上講,我想創建一個模塊(infras.R),以包含鏈接到checkboxInputs的大量watchEvent函數。

我了解我需要在app.R中獲取模塊,將observeEvent包裝在函數中,在observeEvent函數中包含輸入ID的名稱空間(ns),並為該函數插入callModule。 我還將callModule封裝在ObserveEvent中,以便其功能持久存在,並且不會在啟動Webapp后僅觸發一次。

在運行app.R時輸出以下錯誤,但我不確定如何解決:

Warning: Error in proxy: could not find function "proxy"
   81: eval
   80: eval
   79: %>%
   78: module [infras.R#153]
   73: callModule
   72: observeEventHandler  
    1: runApp

感謝您的協助,因為我發現找到有關如何執行此操作的文獻非常困難。

我的R腳本中的關鍵片段。

infras.R(更新):

icons_pow <- awesomeIcons(
  iconColor = 'white',
  markerColor = 'green',
  text = "m"
)

mod <- function(input, output, session, pow_id, prox){

observeEvent(pow_id(),{
  if(pow_id() != 0){
     pow_id <- readOGR("../geospatial_files/ind", layer = "plants")
     pow_iddf <- as.data.frame(pow_id)
     prox %>%
       addAwesomeMarkers(lng=pow_iddf$coords.x1, lat=pow_iddf$coords.x2, group = "pow_idg", icon=icons_pow,
                    label = paste(pow_iddf$Name,pow_iddf$Power_type,sep = ", "))
  }
  else {prox %>% clearGroup("pow_idg") %>% removeControl(layerId="pow_idc")
  }
}
)
}

app.R(已更新):

...
source("infras.R")
...

server <- function(input, output, session) {
...

proxy <- leafletProxy("map")
callModule(mod, "mod", reactive(input$pow_id), proxy)


  })
...

}

您需要將input對象包裝為reactive並將其用作模塊的輸入參數。 另一個輸入參數是您的傳單代理。 在模塊內部,您可以使用observe更改代理,然后立即對其進行更新:

library(shiny)
library(leaflet)
library(RColorBrewer)

# The module containing the observer. Input is the reactive handle of legend input and the proxy
mod <- function(input, output, session, legend, prox){

  observe({
    prox %>% clearControls()
    if (legend()) {
      prox %>% addLegend(position = "bottomright",
                            pal = colorNumeric("Blues", quakes$mag), values = ~mag
      )
    }
  })

}

ui <- bootstrapPage(
  checkboxInput("legend", "Show legend", TRUE),
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%")
)

server <- function(input, output, session) {

  output$map <- renderLeaflet({
    pal <- colorNumeric("Blues", quakes$mag)
    leaflet(quakes) %>% addTiles() %>%      
      addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
                 fillColor = ~pal(mag), fillOpacity = 0.7, popup = ~paste(mag)) %>% 
      fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
  })

  # This is the handle for map
  proxy <- leafletProxy("map", data = quakes)
  callModule(mod, "mod", reactive(input$legend), proxy)


}

shinyApp(ui, server)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM