And*_*rii 1 r radio-button shiny
我有一个带有单选按钮的 R Shiny UI 组件,并且想手动更改代码中选定的值。
假设有 3 个值:“留在此处”、“执行”和“离开”。通过选择“Do it”,用户会看到操作按钮“Do it”。我想在用户单击操作按钮“Do it”后更改“stay_here”上选定的单选按钮值。这是代码。
library(shiny)
# UI
ui <- fluidPage(
fluidPage(
fluidRow(uiOutput("rbtn_test")),
fluidRow(uiOutput("uo_stay_here")),
fluidRow(uiOutput("uo_do_it")),
fluidRow(uiOutput("uo_go_away"))))
# SERVER
server <- function(input, output) {
# 1. Radio buttons
output$rbtn_test <- renderUI({
# 1.1. Values
actions_values <- c("stay_here", "do_it", "go_away")
names(actions_values) <- c("Stay here", "Do it", "Go away")
# 1.2. Selected value
action_selected <- "stay_here"
# 1.3. UI element
radioButtons(
"rbtn_test_selected", "Actions",
choices = actions_values,
selected = action_selected,
inline = TRUE)
})
# 2. 'Stay here'
output$uo_stay_here <- renderUI({
if(input$rbtn_test_selected == "stay_here") {
tags$div(tags$p("Stay here ..."))
}
})
# 3. Process 'Do it' action
output$uo_do_it <- renderUI({
if(input$rbtn_test_selected == "do_it") {
actionButton("btn_doit", "Do it")
# TBD: Change selected value in radio buttons on 'stay_here'
}
})
# 4. 'Go away'
output$uo_go_away <- renderUI({
if(input$rbtn_test_selected == "go_away") {
tags$div(tags$p("Go away ..."))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
谢谢!
您可以添加一个observeEvent“执行”操作按钮,该按钮将在单击时更改所选值。
observeEvent(input$btn_doit, {
updateRadioButtons(session, "rbtn_test_selected", selected = "stay_here")
})
Run Code Online (Sandbox Code Playgroud)
完整代码-
library(shiny)
# UI
ui <- fluidPage(
fluidPage(
fluidRow(uiOutput("rbtn_test")),
fluidRow(uiOutput("uo_stay_here")),
fluidRow(uiOutput("uo_do_it")),
fluidRow(uiOutput("uo_go_away"))))
# SERVER
server <- function(input, output, session) {
# 1. Radio buttons
output$rbtn_test <- renderUI({
# 1.1. Values
actions_values <- c("stay_here", "do_it", "go_away")
names(actions_values) <- c("Stay here", "Do it", "Go away")
# 1.2. Selected value
action_selected <- "stay_here"
# 1.3. UI element
radioButtons(
"rbtn_test_selected", "Actions",
choices = actions_values,
selected = action_selected,
inline = TRUE)
})
# 2. 'Stay here'
output$uo_stay_here <- renderUI({
if(input$rbtn_test_selected == "stay_here") {
tags$div(tags$p("Stay here ..."))
}
})
# 3. Process 'Do it' action
output$uo_do_it <- renderUI({
if(input$rbtn_test_selected == "do_it") {
actionButton("btn_doit", "Do it")
}
})
observeEvent(input$btn_doit, {
updateRadioButtons(session, "rbtn_test_selected", selected = "stay_here")
})
# 4. 'Go away'
output$uo_go_away <- renderUI({
if(input$rbtn_test_selected == "go_away") {
tags$div(tags$p("Go away ..."))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)