闪亮随机默认

时间:2019-04-02 04:03:11

标签: r shiny

我希望为每次刷新页面时都会更改的闪亮应用程序提供默认选择。因此,例如,在Hello World Shiny演示中,我希望默认选择为500

,而不是将默认选择为sample(1:1000,1)

http://shiny.rstudio.com/gallery/example-01-hello.html

我尝试将随机生成的值直接放在value =部分中,但这似乎仅在启动应用程序时才更新,而不是在每次加载页面时更新。

如何进行随机默认设置?

2 个答案:

答案 0 :(得分:1)

您需要使用反应式UI元素。

library(shiny)

ui <- fluidPage(

  # Application title
  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarLayout(
    sidebarPanel(
uiOutput("slider")
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)


server <- function(input, output) {

  # Expression that generates a plot of the distribution. The expression
  # is wrapped in a call to renderPlot to indicate that:
  #
  #  1) It is "reactive" and therefore should be automatically 
  #     re-executed when inputs change
  #  2) Its output type is a plot 
  #

  output$slider <- renderUI({
    sliderInput("obs", 
                "Number of observations:", 
                min = 1, 
                max = 1000, 
                value =runif(1,1,1000))

  })
  output$distPlot <- renderPlot({
    req(input$obs)
    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })
}

  shinyApp(ui = ui, server = server)

这将在滑块中随机选择一个新值。这是你所追求的吗?

答案 1 :(得分:1)

我们可以使用updateSliderInput,例如

server <- function(input, output, session) {
  observe({
    updateSliderInput(session, "bins", value = sample(1:500,1))
  })

 ....
}

别忘了在 server 函数定义中添加 session 变量并在 sliderInput 中更新 max 值到500。