假设您不想要一个初始值,因为它会被观察到,似乎有 3 种解决方案:
- 使用额外的选项,例如称为 'none' 参见 radioButtons 帮助
- 使用字符 (0)(参见 radioButtons 帮助)
- 使用额外的 actionButton 并观察该按钮。
如果您不想使用额外的 radioButtons 选项或 actionButton 来模糊用户界面,请使用 character(0)。
但是,当使用 'character(0)' 时,您可能还需要解决副作用。问题是 'character(0)' 将不会将输入参数重置为 NULL,因此您不能两次使用相同的选项(这可能是可取的,也可能不是可取的)。这显示在以下示例程序。
server <- function(input, output) {
output$uiRadioButtons <- renderUI({ radioButtons (inputId='actionId', label='action:', choices = c ('a', 'b', 'c'), selected=character(0)) })
n <- 0
observe({
actionId <- input$actionId
n <<- n+1
if (!is.null(actionId)) {
if (actionId=='a') output$action <- renderText (paste (n, "action A"))
if (actionId=='b') output$action <- renderText (paste (n, "action B"))
if (actionId=='c') output$action <- renderText (paste (n, "action C"))
output$uiRadioButtons <- renderUI({ radioButtons (inputId='actionId', label='action:', choices = c ('a', 'b', 'c'), selected=character(0)) })
} else output$action <- renderText ("actionId equals NULL")
}) }
ui <- fluidPage (
sidebarLayout(
sidebarPanel ( uiOutput('uiRadioButtons')),
mainPanel (uiOutput('action'))
) )
shinyApp (ui = ui, server = server)
这可以通过使用和观察虚拟单选按钮来解决(尽管对于远程应用程序可能太慢),如下所示。
server <- function(input, output) {
showActions <- function() {
output$uiRadioButtons <- renderUI ({ radioButtons (inputId='actionId', label='action:', choices = c ('a', 'b', 'c'), selected=character(0)) })
}
showActions()
n <- 0
observe({
actionId <- input$actionId
n <<- n+1
if (!is.null(actionId)) {
if (actionId=='dummy') showActions ()
else {
if (actionId=='a') output$action <- renderText (paste (n, "action A"))
if (actionId=='b') output$action <- renderText (paste (n, "action B"))
if (actionId=='c') output$action <- renderText (paste (n, "action C"))
output$uiRadioButtons <- renderUI({ radioButtons (inputId='actionId', label='action:', choices = 'dummy') })
}
} else output$action <- renderText ("actionId equals NULL")
})
}
ui <- fluidPage (
sidebarLayout(
sidebarPanel (
# radioButtons (inputId='objectId', label='selct object:', choices = c ('o1', 'o2', 'o3'), inline = TRUE),
uiOutput('uiRadioButtons')
),
mainPanel (uiOutput('action'))
)
)
shinyApp (ui = ui, server = server)
它看起来很难看,但它很有效,我会很高兴,如果有人能给我一个更好的解决方案,例如一种将输入变量重置为 NULL 的方法。