【问题标题】:Enable observeEvent to trigger a eventReactive event启用 observeEvent 以触发 eventReactive 事件
【发布时间】:2020-09-29 11:41:28
【问题描述】:

我有一个我正在尝试做的小例子:

我正在生成数据sims 的正态分布,该分布会根据按下的按钮而变化。前 5 个值打印在第一个输出框中。由此,我们收集数据样本并计算每个样本的平均值 - samp_sims。随着滑块的移动,样本大小会发生变化,第二个输出框中的均值也会发生变化。

当滑块移动时,人口值sims 不会改变是可以的。但是,如果用户在“optionB”之后单击“optionA”,则人口sims 数字会发生变化 - 但样本平均数(底部的输出 2)不会更新 - 它们仍然来自上一个选项。在滑块再次移动之前,它们不会更新。我希望它们也能在按下按钮时自动更新。我尝试使用 observeEvent() 操作来执行此操作 - 将我的 eventReactive() 事件的相同代码放入其中,但这不起作用。

有没有办法确保在滑块移动或按下按钮时更新samp_sims 值?

---
title: "test"
author: "James"
date: "9/28/2020"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r, echo=FALSE}

radioButtons("go", h3(""),
             choices = list("optionA" = 10,
                            "optionB" = 20),
             inline = TRUE
             )


```      


```{r, echo=FALSE}

 sliderInput("sampsize", label = "Sample Size:",
              min = 5, max = 100, value = 10, step = 1)
```


```{r, echo=FALSE}
sims <- eventReactive(input$go, {
 rnorm(1000, mean = as.numeric(input$go), sd = 2.5)
})
```


```{r, echo = FALSE}
    samp_sims <- eventReactive(input$sampsize , {
     apply(replicate(100, sample(sims(), input$sampsize, T)),2,mean)
  })
```

```{r,echo=FALSE}
observeEvent(input$go, {
})
```


```{r, echo=FALSE}
renderPrint({ sims()[1:5]})
```

```{r, echo=FALSE}
renderPrint({ samp_sims()[1:5]})
```

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您应该为eventReactive 尝试两个事件中的list()。在你的情况下,

    samp_sims <- eventReactive(list(input$sampsize,input$go) , {
      apply(replicate(100, sample(sims(), input$sampsize, T)),2,mean)
    })
    

    下面是一个工作示例

    library(shiny)
    
    ui <- fluidPage( 
      
      sidebarLayout(
        sidebarPanel(
          actionButton("t1", "t1"),
          actionButton("t2", "t2")
        ),
        
        mainPanel(
          verbatimTextOutput("view")
        )
      )
    )
      
    server <- function(input, output) {
      
      view <- eventReactive(list(input$t1, input$t2),{
        t1 <- input$t1              
        t2 <- input$t2
        
        rnorm(1)
      })
      
      output$view <- renderPrint(view())
      
    }
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 2019-07-14
      • 1970-01-01
      • 2020-12-04
      • 2018-12-14
      • 2019-08-01
      • 2018-03-12
      • 2020-01-16
      • 2019-09-15
      相关资源
      最近更新 更多