简介
在shinyApp
中,我想用动态输入渲染输出。
我的问题是,使用带有不同标签的shinydashboard
,只有在激活相应标签时才会呈现*Input()
的默认值(想想输入和输出标签)。
在一个简单示例中对switch
值使用input$*
语句时,我得到相同的行为(除非在呈现输入后,switch
确实起作用并且输出出现)。请参阅以下内容:
代码
library(shiny)
shinyApp(
ui = shinyUI(fluidPage(sidebarLayout(sidebarPanel(uiOutput("select_bin")),
mainPanel( plotOutput("distPlot"))))),
server = function(input, output) {
output$select_bin <- renderUI({
selectInput("bins", "Number of bins:", c("few", "many"))
})
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- switch(input$bins, few = 10L, many = 100L)
bins <- seq(min(x), max(x), length.out = bins)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
上面的代码有效,但会抛出
Warning: Error in switch: EXPR must be a length 1 vector
。
我认为input$bins
在呈现selectInput
之前不可用。
问题
如何为input$bins
定义默认值,因此在呈现selectInput
之前,renderPlot
中的表达式不会抛出警告?
第一种方法
我尝试在this post中使用observe
,但我不确定它的确切含义,因此很难解决问题。
library(shiny)
shinyApp(
ui = shinyUI(fluidPage(sidebarLayout(sidebarPanel(uiOutput("select_bin")),
mainPanel( plotOutput("distPlot"))))),
server = function(input, output) {
output$select_bin <- renderUI({
selectInput("bins", "Number of bins:", c("few", "many"))
})
observe({
bins <- switch(input$bins, few = 10L, many = 100L)
bins
})
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = bins)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
根本不起作用并抛出额外的Warning: Error in seq.default: object 'bins' not found
。
答案 0 :(得分:1)
使用
reactiveValues
创建默认列表,observeEvent
代表input$bins
,更新默认值似乎解决了这个问题:
library(shiny)
shinyApp(
ui = shinyUI(fluidPage(sidebarLayout(sidebarPanel(uiOutput("select_bin")),
mainPanel( plotOutput("distPlot"))))),
server = function(input, output) {
values <- reactiveValues(bins = 10L)
output$select_bin <- renderUI({
selectInput("bins", "Number of bins:", c("few", "many"))
})
observeEvent(input$bins, {
values$bins <- switch(input$bins, few = 10L, many = 100L)
})
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = values$bins)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
答案 1 :(得分:1)
req()
中需要renderPlot()
。只有当req()
不为空时,input$bins
才能表明该情节。
library(shiny)
shinyApp(
ui =
shinyUI(fluidPage(sidebarLayout(sidebarPanel(uiOutput("select_bin")),
mainPanel(
plotOutput("distPlot"))))),
server = function(input, output) {
output$select_bin <- renderUI({
selectInput("bins", "Number of bins:", c("few", "many"))
})
output$distPlot <- renderPlot({
req(input$bins)
x <- faithful[, 2]
bins <- switch(input$bins, few = 10L, many = 100L)
bins <- seq(min(x), max(x), length.out = bins)
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})