gpt4 book ai didi

r - 更改选择选项但保留以前选择的值

转载 作者:行者123 更新时间:2023-12-04 10:36:19 25 4
gpt4 key购买 nike

问题

我有两个下拉菜单,dd2 中可用的选项取决于 dd1 中选择的选项。我无法弄清楚如何更改下拉列表 2 的选项,但保留已经做出的任何选择。我还应该能够从先前选择到下拉列表 2 中删除项目。

示例

假设 dd1 是 Country: India, England, USA 以及 dd2, City: (New Delhi, Mumbai), (London, Birmingham), (New York, Washington DC) 中的相应选项。我先选印度,再选孟买,再选英格兰,保留孟买,加上伦敦。然后我以类似的方式添加纽约。我现在意识到我不需要孟买,所以我删除了它,让我留在伦敦和纽约。

尝试失败

我正在尝试诸如将选择附加到先前存在的向量并将两个向量的交集传递给 'selected' 参数之类的事情,但它似乎不起作用。我猜这样做的循环性质可能会导致问题。

基本码

为了节省你们一些时间并让我们有相同的引用 -

# server.r

library(shiny)
library(data.table)
countrycity = data.table(
country = c('India','India','England','England','USA','USA'),
city = c('New Delhi','Mumbai','London','Birmingham','New York','Washington DC')
)

shinyServer(function(input, output) {

# dd1: country
output$chooseCountry <- renderUI({
selectizeInput(
"countrSelected",
"Country",
as.list(c('All',unique(unique(countrycity$country)))),
options = list(create = TRUE),
selected = c('All'),
multiple = TRUE,
width="120px"
)
})

# filtering list of cities based on the country selected
citiestoshow = reactive({

countryselected = if ( is.null(input$countryselected) ) {
unique(countrycity$country)
} else if ( 'All' %in% input$countryselected ) {
unique(countrycity$country)
} else {
input$countryselected
}

countrycity[country %in% countryselected, city]

})

# dd2: city
output$choosecities <- renderUI({

selectizeInput(
'cityselected',
label = 'City',
choices = as.list(c('All',citiestoshow())),
options = list(create = TRUE),
multiple = TRUE,
width="120px"
)

})


}

最佳答案

如果有人仍在寻找一个简单的例子来更新选择,同时保持以前选择的值:

#in ui.R you have a selectInput that you want to update
selectInput(inputId = "mymenu", label = "My Menu",
choices = c("A" = "a","B" = "b","C" = "c"),
selected = c("A" = "a"))


# in server.R create reactiveVal
current_selection <- reactiveVal(NULL)

# now store your current selection in the reactive value
observeEvent(input$mymenu, {
current_selection(input$mymenu)
})

#now if you are updating your menu
updateSelectInput(session, inputId = "mymenu",
choices = c("A" = "a","B" = "b","C" = "c", "D" = "d"),
selected = current_selection())

关于r - 更改选择选项但保留以前选择的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28379937/

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