该代码仅在我添加变量并首次删除时才起作用。删除该变量后,它返回到选择“添加到地块”中,然后无法将其添加回去,我想当我更新updateSelectInput
时,出现了问题。加selectRemove
为空时需要删除。如何通过两种方式进行更新?
library(shiny)
mtcars_1 <- mtcars[,c("mpg", "disp", "hp", "drat", "wt", "qsec")]
runApp(list(
ui=pageWithSidebar(headerPanel("Adding and Removing Variables"),
sidebarPanel(
selectInput(inputId = "selectAdd", label = "Add to the plot",
choices = c(names(mtcars_1)),
selected = names(mtcars_1)[1]),
actionButton(inputId = "add", label = "Add to the plot")
),
mainPanel(
textOutput("text"),hr(),
uiOutput("remove_list")
)
),
server=function(input, output, session) {
rv <- reactiveValues(add_v = c())
observeEvent(input$add,{
rv$add_v <- rbind(rv$add_v,input$selectAdd)
})
rv <- reactiveValues(rem_v = c())
observeEvent(input$remove,{
rv$rem_v <- rbind(rv$rem_v,input$selectRemove)
})
observe({
value_add <- c(names(mtcars_1)[!names(mtcars_1) %in% rv$add_v ],rv$rem_v)
value_rem <-c(rv$add_v[! rv$add_v %in% rv$rem_v])
updateSelectInput(session,"selectAdd",choices = value_add)
updateSelectInput(session,"selectRemove",choices = value_rem)
})
output$remove_list <- renderUI({
if(length(rv$add_v) > 0){
tagList(
selectInput(inputId = "selectRemove", label = "Remove to the plot",
choices = c(rv$add_v),
selected = rv$add_v[1]),
actionButton(inputId = "remove", label = "Remove to the plot")
)
}
})
output$text <- renderText({
c(rv$add_v[! rv$add_v %in% rv$rem_v])
})
}))
答案 0 :(得分:0)
欢迎来到stackoverflow!
您快到了-但是,您对reactiveValues
的更新逻辑还不完整。对于每个按钮单击,您都必须将一个对象添加到一个值,然后将其从另一个值中删除。请检查以下内容:
library(shiny)
mtcars_1 <- mtcars[, c("mpg", "disp", "hp", "drat", "wt", "qsec")]
runApp(list(
ui = pageWithSidebar(
headerPanel("Adding and Removing Variables"),
sidebarPanel(
selectInput(
inputId = "selectAdd",
label = "Add to the plot",
choices = names(mtcars_1),
selected = names(mtcars_1)[1]
),
actionButton(inputId = "add", label = "Add to the plot")
),
mainPanel(textOutput("text"), hr(),
uiOutput("remove_list"))
),
server = function(input, output, session) {
rv <- reactiveValues(add_v = NULL, rem_v = names(mtcars_1))
observeEvent(input$add, {
rv$rem_v <- setdiff(rv$rem_v, input$selectAdd)
rv$add_v <- union(rv$add_v, input$selectAdd)
})
observeEvent(input$remove, {
rv$add_v <- setdiff(rv$add_v, input$selectRemove)
rv$rem_v <- union(rv$rem_v, input$selectRemove)
})
observe({
updateSelectInput(session, "selectAdd", choices = rv$rem_v)
updateSelectInput(session, "selectRemove", choices = rv$add_v)
})
output$remove_list <- renderUI({
if (length(rv$add_v) > 0) {
tagList(
selectInput(
inputId = "selectRemove",
label = "Remove to the plot",
choices = c(rv$add_v),
selected = rv$add_v[1]
),
actionButton(inputId = "remove", label = "Remove to the plot")
)
}
})
output$text <- renderText({
c(rv$add_v[!rv$add_v %in% rv$rem_v])
})
}
))