Shiny 和 R:在代码中而不是通过鼠标更改 ui 反应值

Shiny and R: changing ui reactive values in code and not by mouse

我正在尝试编写一个简单的示例,我可以在其中更改反应源,不是通过鼠标交互,而是通过将该反应源的值更改为 R 代码。

这是一个工作示例:

ui.R :

# coming from 001-helloworld example....
library(shiny)

shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server.R :

library(shiny)

shinyServer(function(input, output) {

  output$distPlot <- renderPlot({
    x    <- faithful[, 2]  # Old Faithful Geyser data
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })

})

我希望能够在 R 代码中访问和更改 "bins" 并使图表对此做出反应(不使用鼠标)。

编辑:澄清一下,bin 的变化应该在运行时在 R 代码中产生(一旦闪亮的 "app" 是 运行)。所以,这就像 "replacing" 鼠标交互与 "code in runtime" 交互。

有办法吗? 我肯定会在这里漏掉一些明显的要点……抱歉。

谢谢。

简短的回答是否定的。一旦将某物设为反应源,就无法对其进行修改,除非是反应性的。主要问题是,如果一个值或输出应该更新以反映用户所做的更改,然后程序更改它 - 它是否应该改回用户指示的内容。有关这方面的更多讨论,请参阅 here

但是,您可以让应用决定是使用反应值(input$bins 此处)还是其他值。下面是一个简短的应用程序,它 this.If 用户选择超过 25 个容器,该应用程序将使用 3 个。

library(shiny)
runApp(list(
  ui=fluidPage(
    titlePanel("Hello Shiny!"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("bins",
                    "Number of bins:",
                    min = 1,
                    max = 50,
                    value = 30)
      ),
      mainPanel(
        plotOutput("distPlot")
      )
    )
  ),

  server=function(input, output) {

    output$distPlot <- renderPlot({
      x    <- faithful[, 2]  # Old Faithful Geyser data
      bins <- seq(min(x), max(x), length.out = if(input$bins>25) {4} else{input$bins + 1})
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })

  }
))

例如,您还可以使用一个 checkboxInput 来选择反应变量或非反应变量。您还可以使用比此处演示的更复杂的逻辑,但这应该能为您提供总体思路。