如何在 Shiny 应用程序中更新 selectModUI 中的传单地图?

2024-01-02

我想更新selectModUI来自mapedit包针对不同的leaflet使用时的地图Shiny。下面是一个工作示例。

library(tidyverse)
library(shiny)
library(sf)
library(leaflet)
library(mapview)
library(mapedit)
library(DT)
library(viridis)

# Load the sf object
nc <- st_read(system.file("shape/nc.shp", package = "sf"))

# Project transformation
nc <- st_transform(nc, crs = 4326)

# Create a color function for the leaflet map
sid74_pal <- colorBin(palette = viridis(10), domain = nc$SID74, bins = 4)

# Create a leaflet map
sid74_map <- leaflet() %>%
  addTiles(group = "OSM") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
  addFeatures(nc, 
              color = ~sid74_pal(SID74), 
              label = ~htmltools::htmlEscape(NAME),
              layerId = ~seq_len(length(st_geometry(nc)))) %>%
  addLegend(position = "bottomright", pal = sid74_pal, 
            values = nc$SID74,
            title = "SID74") %>%
  addLayersControl(baseGroups = c("OSM", "CartoDB", "Esri.WorldImagery"))

ui <- fluidPage(
  # Select Module Output
  h3("Map"),
  selectModUI(id = "Sel_Map"),
  # Datatable Output
  h3("Table"),
  dataTableOutput(outputId = "Table")
)

server <- function(input, output) {
  # Create selectMod
  sel <- callModule(selectMod, "Sel_Map", sid74_map)

  # Reactive values
  rv <- reactiveValues(
    selectnum = NULL,
    sub_table = nc %>% 
      st_set_geometry(NULL) %>%
      slice(0)
  )

  # Subset the table based on the selection
  observe({
    # the select module returns a reactive
    gs <- sel()
    # Filter for the county data
    rv$selectnum <- as.numeric(gs[which(gs$selected == TRUE), "id"])

    if (!is.null(rv$selectnum)){
      rv$sub_table <- nc %>% 
        st_set_geometry(NULL) %>%
        slice(rv$selectnum) 
    }
  })

  # Create a datatable
  output$Table <- renderDataTable({
    datatable(rv$sub_table, options = list(scrollX = TRUE))
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

这个想法是创建一个地图,用户可以选择或取消选择地图上的多边形。根据用户的选择,数据表输出将动态显示选择了哪些县并显示数据,如屏幕截图所示。

现在我想添加一个选择输入,以便用户可以决定他们想要使用该应用程序可视化的参数。我觉得我可以创建某种反应性或反应性值来存储地图,然后更新下面是我创建的示例。请注意,与示例 1 相比,我创建了一个新的传单地图,名为sid79_map在示例 2 中添加一个选择输入,以便人们可以选择。然而,这个策略并不奏效。如果有人能指出一个方向,那就太好了。

library(tidyverse)
library(shiny)
library(sf)
library(leaflet)
library(mapview)
library(mapedit)
library(DT)
library(viridis)

# Load the sf object
nc <- st_read(system.file("shape/nc.shp", package = "sf"))

# Project transformation
nc <- st_transform(nc, crs = 4326)

# Create a color function for the leaflet map
sid74_pal <- colorBin(palette = viridis(10), domain = nc$SID74, bins = 4)
sid79_pal <- colorBin(palette = viridis(10), domain = nc$SID79, bins = 4)

# Create a leaflet map
sid74_map <- leaflet() %>%
  addTiles(group = "OSM") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
  addFeatures(nc, 
              color = ~sid74_pal(SID74), 
              label = ~htmltools::htmlEscape(NAME),
              layerId = ~seq_len(length(st_geometry(nc)))) %>%
  addLegend(position = "bottomright", pal = sid74_pal, 
            values = nc$SID74,
            title = "SID74") %>%
  addLayersControl(baseGroups = c("OSM", "CartoDB", "Esri.WorldImagery"))

sid79_map <- leaflet() %>%
  addTiles(group = "OSM") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
  addFeatures(nc, 
              color = ~sid79_pal(SID79), 
              label = ~htmltools::htmlEscape(NAME),
              layerId = ~seq_len(length(st_geometry(nc)))) %>%
  addLegend(position = "bottomright", pal = sid79_pal, 
            values = nc$SID79,
            title = "SID79") %>%
  addLayersControl(baseGroups = c("OSM", "CartoDB", "Esri.WorldImagery"))

ui <- fluidPage(
  # Select input
  selectInput(inputId = "Selection", label = "Select Counties", choices = c("SID74", "SID79"), selected = "SID74"),
  # Select Module Output
  h3("Map"),
  selectModUI(id = "Sel_Map"),
  # Datatable Output
  h3("Table"),
  dataTableOutput(outputId = "Table")
)

server <- function(input, output) {

  # Try to create reactivity based on the select input type, not working
  sel_type <- reactive({
    input$Selection
  })

  leafmap <- reactive({
    if(sel_type() == "SID74"){
      sid74_map
    } else if (sel_type() == "SID79"){
      sid79_map
    }
  })

  # Create selectMod
  sel <- callModule(selectMod, "Sel_Map", leafmap())

  # Reactive values
  rv <- reactiveValues(
    selectnum = NULL,
    sub_table = nc %>% 
      st_set_geometry(NULL) %>%
      slice(0)
  )

  # Subset the table based on the selection
  observe({
    # the select module returns a reactive
    gs <- sel()
    # Filter for the county data
    rv$selectnum <- as.numeric(gs[which(gs$selected == TRUE), "id"])

    if (!is.null(rv$selectnum)){
      rv$sub_table <- nc %>% 
        st_set_geometry(NULL) %>%
        slice(rv$selectnum) 
    }
  })

  # Create a datatable
  output$Table <- renderDataTable({
    datatable(rv$sub_table, options = list(scrollX = TRUE))
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

主要问题是你的callModule()需要处于反应式上下文中。 我稍微修改了你的示例来解决这个问题,使用observeEvent().

见下文(我导入dplyr::slice因为我想避免加载完整的tidyverse).

Edit:我做了一些进一步的清理并添加了一个自定义版本selectMod回应OP的评论。

library(shiny)
library(sf)
library(leaflet)
library(mapview)
library(mapedit)
library(DT)
library(viridis)

# Load the sf object
nc <- st_read(system.file("shape/nc.shp", package = "sf"))

# Project transformation
nc <- st_transform(nc, crs = 4326)

# Create a color function for the leaflet map
sid74_pal <- colorBin(palette = viridis(10), domain = nc$SID74, bins = 4)
sid79_pal <- colorBin(palette = viridis(10), domain = nc$SID79, bins = 4)

# Create a leaflet map
sid74_map <- leaflet() %>%
  addTiles(group = "OSM") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
  addFeatures(nc,
              color = ~sid74_pal(SID74),
              label = ~htmltools::htmlEscape(NAME),
              layerId = ~seq_len(length(st_geometry(nc)))) %>%
  addLegend(position = "bottomright", pal = sid74_pal,
            values = nc$SID74,
            title = "SID74") %>%
  addLayersControl(baseGroups = c("OSM", "CartoDB", "Esri.WorldImagery"))

sid79_map <- leaflet() %>%
  addTiles(group = "OSM") %>%
  addProviderTiles("CartoDB", group = "CartoDB") %>%
  addProviderTiles("Esri.WorldImagery", group = "Esri.WorldImagery") %>%
  addFeatures(nc,
              color = ~sid79_pal(SID79),
              label = ~htmltools::htmlEscape(NAME),
              layerId = ~seq_len(length(st_geometry(nc)))) %>%
  addLegend(position = "bottomright", pal = sid79_pal,
            values = nc$SID79,
            title = "SID79") %>%
  addLayersControl(baseGroups = c("OSM", "CartoDB", "Esri.WorldImagery"))

selectMod <- function(input, output, session, leafmap,
                      styleFalse = list(fillOpacity = 0.2, weight = 1, opacity = 0.4),
                      styleTrue = list(fillOpacity = 0.7, weight = 3, opacity = 0.7))
{
  print("*** custom selectMod")
  output$map <- leaflet::renderLeaflet({
    mapedit:::add_select_script(leafmap, styleFalse = styleFalse, styleTrue = styleTrue,
                                ns = session$ns(NULL))
  })
  id <- "mapedit"
  select_evt <- paste0(id, "_selected")
  df <- data.frame()
  selections <- reactive({
    id <- as.character(input[[select_evt]]$id)
    if (length(df) == 0) {
      # Initial case, first time module is called.
      # Switching map, i.e. subsequent calls to the module.
      # Note that input[[select_evt]] will always keep the last selection event,
      # regardless of this module being called again.
      df <<- data.frame(id = character(0), selected = logical(0),
                        stringsAsFactors = FALSE)
    } else {
      loc <- which(df$id == id)
      if (length(loc) > 0) {
        df[loc, "selected"] <<- input[[select_evt]]$selected
      } else {
        df[nrow(df) + 1, ] <<- c(id, input[[select_evt]]$selected)
      }
    }
    return(df)
  })
  return(selections)
}


ui <- fluidPage(
  # Select input
  selectInput(inputId = "Selection", label = "Select Counties", choices = c("SID74", "SID79"), selected = "SID74"),
  # Select Module Output
  h3("Map"),
  selectModUI(id = "Sel_Map"),
  # Datatable Output
  h3("Table"),
  dataTableOutput(outputId = "Table")
)

server <- function(input, output) {

  # Reactivity based on the select input type
  leafmap <- reactive({
    my_sel <- input$Selection
    if (my_sel == "SID74") {
      sid74_map
    } else if (my_sel == "SID79") {
      sid79_map
    }
  })

  # Reactive values
  rv <- reactiveValues(
    sel = reactive({}),
    selectnum = NULL,
    sub_table = nc %>%
      st_set_geometry(NULL) %>%
      dplyr::slice(0)
  )

  # Create selectMod
  observeEvent(leafmap(),
    rv$sel <- callModule(selectMod, "Sel_Map", leafmap())
  )

  # Subset the table based on the selection
  observeEvent(rv$sel(), {
    # The select module returns a reactive
    gs <- rv$sel()
    # Filter for the county data
    rv$selectnum <- as.numeric(gs[which(gs$selected == TRUE), "id"])

    rv$sub_table <- nc %>%
      st_set_geometry(NULL) %>%
      dplyr::slice(rv$selectnum)
  })

  # Create a datatable
  output$Table <- renderDataTable({
    datatable(rv$sub_table, options = list(scrollX = TRUE))
  })

}

# Run the application
shinyApp(ui = ui, server = server)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Shiny 应用程序中更新 selectModUI 中的传单地图? 的相关文章

  • 在 R 中进行 Cox 回归后,将预测危险比列添加到数据帧中

    在 R 中运行 Cox PH 回归后 我需要在数据框中添加预测风险比的列 数据框是面板数据 其中 numgvkey 如果公司标识符 和年龄是时间标识符 您可以从此链接下载一小部分日期 https drive google com file
  • 如何使用 r 中的 caret 包在最佳调整超参数的 10 倍交叉验证中获得每次折叠的预测?

    我试图使用 R 中的插入符包使用 10 倍交叉验证和 3 次重复来运行 SVM 模型 我想使用最佳调整的超参数获得每次折叠的预测结果 我正在使用以下代码 Load packages library mlbench library caret
  • 在 mac (iMac OSX ) 终端中远程运行脚本(r 脚本)到其他计算机

    我有一个小示例脚本 script p r 如下所示 打算在终端中运行 usr bin Rscript sink output capture txt mn lt mean 1 10 and so on much longer list of
  • 如何让R使用所有处理器?

    我有一台运行 Windows XP 的四核笔记本电脑 但查看任务管理器 R 似乎一次只使用一个处理器 如何让 R 使用全部四个处理器并加速我的 R 程序 我有一个基本系统 我使用它在 for 循环上并行化我的程序 一旦您了解需要做什么 此方
  • ggplot 中的错误问题:“grid.Call(”L_textBounds“, as.graphicsAnnot(x$label), x$x, x$y, … 中的错误”[重复]

    这个问题在这里已经有答案了 我试图在 ggplot 中制作一个条形图 其中我通过强制其中一些标签为长度为零的字符串 即 来指定要显示的标签 但是 我收到错误 Error in grid Call L textBounds as graphi
  • 如何获得属于五分位数的x?

    我正在大学学习使用 R 进行计量经济学项目 所以请原谅我的笨拙 基本上 使用并给出 一个矩阵 股票价格 行 天 列 公司股票价格 另一个矩阵 市值 行 天 列 公司市值 我必须收集第三个矩阵每天观察的属于市值分布第一五分位数的股票价格 然后
  • 错误:“rjags”的包或命名空间加载失败

    在终端的 conda 环境之一中 我能够成功安装包 rjags 但是 当我在该环境中运行 R 并运行库 rjags 时 出现以下错误 加载所需的包 coda 错误 rjags 的包或命名空间加载失败 rjags 的 loadNamespac
  • 从 R 中的 HTTPS 连接逐行读取

    当创建连接时open r 它允许逐行读取 这对于批量处理大数据流非常有用 例如这个脚本 https gist github com jeroenooms d33a24958d99bb969ac0通过一次读取 100 行来解析相当大的 gzi
  • 在另一个 Rmd 中运行选定的块

    我已经在源 Rmd 文件中运行了分析 并且希望仅使用few来自源的块 我已经看到了一些关于从源 Rmd 中提取所有块的答案来自另一个 Rmd 中的 Rmd 文件的源代码 https stackoverflow com questions 4
  • 比较 R 中的两个字符向量

    我有两个 ID 字符向量 我想比较这两个字符向量 特别是我对以下数字感兴趣 A和B各有多少个ID 有多少个ID在A中但不在B中 有多少个ID在B但不在A 我还想画维恩图 以下是一些可以尝试的基础知识 gt A c Dog Cat Mouse
  • 为绘图制作 2D 图例 - 双变量分区统计图

    我一直在玩双变量 choropleth 地图 并且一直在如何创建类似于 2d 图例的问题上陷入困境约书亚 史蒂文斯 http www joshuastevens net cartography make a bivariate chorop
  • 使用outer代替expand.grid

    我正在寻找尽可能快的速度并留在基地做该做的事expand grid做 我用过outer为过去类似的目的创建一个向量 像这样的东西 v lt outer letters LETTERS paste0 unlist v lower tri v
  • 带 R 的多彩标题

    我想添加颜色某些词在我的图表标题中 我已经能够在这里找到一些先例 http blog revolutionanalytics com 2009 01 multicolor text in r html 具体来说 我希望用撇号括起来的文本 在
  • R:将 JSON 时间格式转换为 POSIX

    我有一个 JSON 字符串 并将其放入数据框中 我能够做到这一点 但我在使用 apply 函数之一将所有时间字符串转换为 POSIX 格式时遇到问题 See here https stackoverflow com questions 90
  • 为什么 geom_boxplot 比基本箱线图识别更多异常值?

    这是一个可重复的示例 与基本箱线图相比 最后一个治疗组又发现了一个异常值 dta lt structure list Treatment c A A A A A A A A A A A A A A A A B B B B B B B B B
  • 16 位以上整数的计算

    我有两个大整数 两者都超过 16 位 确切地说是 20 位 而且我知道由于双精度浮点运算 我在使用这些数字进行计算甚至将它们存储在变量中 独立于编程语言 时受到限制 不过 我想也许gmp图书馆应该处理它们 但不幸的是它没有 可以计算更大的整
  • 如何匹配 R 中的所有匹配项?

    我有 1000 个名字的列表 说A 我还有另外 5 个名字的清单 说B 我想找出这5个名字出现在1000个号码列表中的第几行 例如 Amy 在 A 中可以出现 25 次 B 里有艾米 我想知道 Amy 出现在 A 中的哪些行 我以前使用过
  • R 中的 Websocket

    我设法在 R 中建立到 Mtgox websocket 的连接 规格如下 url https socketio mtgox com mtgox Currency USD https socketio mtgox com mtgox Curr
  • GGPLOT2:如何在 ggplot() 脚本中绘制特定选择

    这是一个名为的大型数据集的峰值P 其中有 10 个优惠 CS 有不同的商店 SHP 具有多个数值 数据集列出了按周排序的它们 WK 2 tm 52 它创建一个大文件 仅前 6 行出现峰值 WK MND CS SHP RevCY RevLY
  • 非闪亮上下文中的反应式对象绑定

    实际问题 你怎样才能近似反应性环境 行为 http shiny rstudio com tutorial lesson6 建立者shiny http shiny rstudio com函数 或者甚至可能在一个函数中使用这些函数无光泽上下文以

随机推荐