gpt4 book ai didi

R Shiny : deselect from selectize

转载 作者:行者123 更新时间:2023-12-01 09:30:28 25 4
gpt4 key购买 nike

首先,我要感谢 Shree,他清理并提高了我以前的代码的性能 here

无论如何,我有一些代码可以让用户选择一个或多个物种(来自 selectizeInput)。该应用程序在 map 上向您显示物种分布。

我现在很疑惑,因为我不能取消选择物种?一旦分布被绘制出来,它们就会留在 map 上,我不能再删除它们了……我一直在仔细查看,但看不到它。我对 shiny 还很陌生。所以这可能是一个容易犯的错误?

下面的所有代码,谢谢!!!乔纳斯

数据框

df<- data.frame(
Number_Total = sample(c("5", "6", "1", "3")),
Species = sample(c("Ilione trifaria", "Pherbellia argyrotarsis",
"Euthycera seguyi", "Ilione trifaria")),
X= sample(c("37", "28", "21", "30")),
Y= sample(c("-5", "-16", "-10", "-15"))
)

界面

ui <- (fluidPage(titlePanel("Species Checker"),  
sidebarLayout(
sidebarPanel(
selectizeInput('species', 'Choose species',
choices = df$Species, multiple = TRUE,
options = list(placeholder = 'select species'))
),
mainPanel(
leafletOutput("CountryMap", width = 600, height = 600))
)
))

服务器

server <- function(input, output, session) {
map_data <- reactive({
#req(input$species)
df[df$Species %in% input$species, ]
})

output$CountryMap <- renderLeaflet({
leaflet() %>% addTiles() %>%
setView(lng = 20, lat = 40, zoom = 2)
})

map_proxy <- leafletProxy("CountryMap")

observe({
md <- map_data()
map_proxy %>%
addCircles(lng = md$Y, lat = md$X, weight = 10,
radius = sqrt(md$Number_Total)*15000, popup = md$Species)
})
}

运行应用程序

shinyApp(ui = ui, server = server)

最佳答案

尝试以下操作(我已经取消引用 df 中的一些变量,否则应用程序会崩溃):

library(tidyverse)
library(shiny)
library(leaflet)

df <- data.frame(
Number_Total = sample(c(5, 6, 1, 3)),
Species = sample(c("Ilione trifaria", "Pherbellia argyrotarsis",
"Euthycera seguyi", "Ilione trifaria")),
X= sample(c(37, 28, 21, 30)),
Y= sample(c(-5, -16, -10, -15))
)

ui <- (fluidPage(titlePanel("Species Checker"),
sidebarLayout(
sidebarPanel(
selectizeInput('species', 'Choose species',
choices = df$Species, multiple = TRUE,
options = list(placeholder = 'select species'))
),
mainPanel(
leafletOutput("CountryMap", width = 600, height = 600))
)
))

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

map_data <- reactive({
#req(input$species)
df[df$Species %in% input$species, ]
})

output$CountryMap <- renderLeaflet({

leaflet() %>% addTiles() %>%
setView(lng = 20, lat = 40, zoom = 2) %>%
addCircles(lng = map_data() %>% pull(Y), lat = map_data() %>% pull(X), weight = 10,
radius = sqrt(map_data() %>% pull(Number_Total))*15000,
popup = map_data() %>% pull(Species))

})

}

shinyApp(ui = ui, server = server)

您需要直接从 reactive 上下文中提取值;我还建议在一份声明中做到这一点,而不是四处传播。

附言如果您的初始数据框确实包含 character 格式的所有变量,您可以在 map_data 部分添加 mutate_at 语句,例如这个:

map_data <- reactive({
#req(input$species)
df[df$Species %in% input$species, ] %>%
mutate_at(vars(c("Number_Total", "X", "Y")), funs(as.numeric))

然后脚本也可以使用此处提供的初始数据框运行,无需手动更改。

关于R Shiny : deselect from selectize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53224887/

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