首页 > 解决方案 > 如何观察两个事件中的任何一个 - 闪亮

问题描述

我有一个像这样的交互式 RMarkdown 文档:

---
title: "CLT"
author: "James"
date: "9/25/2020"
output: html_document
runtime: shiny
---

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


```{r, echo=FALSE}
# two input buttons
inputPanel(
 actionButton("go", "1 sample"),
 actionButton("go2", "20 samples")
)

```

```{r, echo=FALSE}
# population of data
pop1 <- rnorm(100000,10,2.5)
```

```{r, echo = FALSE}
# get mean of one sample if button 1 pressed
Vals <- eventReactive(input$go, {
    mean(sample(pop1, 10, T))
  })
```

```{r, echo = FALSE}
# get means of 20 samples if button 2 pressed
    Vals2 <- eventReactive(input$go2, {
     apply(replicate(20, sample(pop1, 10, T)),2,mean)
  })
```


```{r, echo=FALSE}
# count how many times button 1 is pressed
x <- reactiveVal(0)

  observeEvent(input$go, {
    x(x() + 1)
  })

# add mean of one sample to a vector
  y <- reactiveVal(NA)

    observeEvent(input$go, {
    y(c(y(),Vals()))
  })


```
  
 
```{r, echo=FALSE}
renderPrint({
    x()
  })
```
  
```{r, echo=FALSE}
renderPrint({
    tail(y(),10)
  })
```

我们有两个按钮输入。一个将导致eventReactive()计算一个样本的平均值的事件。另一个导致eventReactive()计算 20 个样本均值的事件。

我希望保留 1) 计数已发生的样本数(每次单击 1 个样本按钮应在计数中添加 1,每次单击 20 个样本按钮应在计数中添加 20)。我也试图通过更新一个向量y()observeEvent()存储我们去的方法。我可以只为一个示例按钮工作,但当我想添加 20 个示例按钮时不行。

例如,假设我点击了一个样本按钮 5 次,但现在我点击了 20 个样本按钮,我希望计数器x()现在显示 25,并且y()应该有 26 个元素(我在第一个元素位置以 NA 开始) .

是否有可能以某种方式与/或反应observeEvent()

标签: rshinyr-markdown

解决方案


这似乎可以根据您的需要工作:

  • x 增加 1 或 20
  • y 正在存储值

我使用NULL而不是NA初始化y,以便第一个元素不为空。
我添加了一个print您可以删除的内容,y以在每次更新后验证控制台中的内容(因为您只是输出tail(y(),10)

---
title: "CLT"
author: "James"
date: "9/25/2020"
output: html_document
runtime: shiny
---
  
  ```{r setup, include=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


```{r, echo=FALSE}
# two input buttons
inputPanel(
  actionButton("go", "1 sample"),
  actionButton("go2", "20 samples")
)

```

```{r, echo=FALSE}
# population of data
pop1 <- rnorm(100000,10,2.5)
```

```{r, echo = FALSE}
# get mean of one sample if button 1 pressed
Vals <- eventReactive(input$go, {
  mean(sample(pop1, 10, T))
})
```

```{r, echo = FALSE}
# get means of 20 samples if button 2 pressed
Vals2 <- eventReactive(input$go2, {
  apply(replicate(20, sample(pop1, 10, T)),2,mean)
})
```


```{r, echo=FALSE}
# count how many times button 1 is pressed
x <- reactiveVal(0)
# add mean of one sample to a vector
y <- reactiveVal(NULL)

observeEvent(input$go, {
  x(x() + 1)
})

observeEvent(input$go2, {
  x(x() + 20)
})


observeEvent(input$go, {
  y(c(y(),Vals()))
})

observeEvent(input$go2, {
  print(y())
  y(c(y(),Vals2()))
})



```


```{r, echo=FALSE}
renderPrint({
  x()
})
```

```{r, echo=FALSE}
renderPrint({
  tail(y(),10)
})
```

在此处输入图像描述


推荐阅读