【发布时间】:2020-09-26 05:40:06
【问题描述】:
我有一个这样的交互式 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)。我也在尝试通过observeEvent() 更新一个向量y() 来存储我们去的方法。我可以仅对一个示例按钮进行此操作,但当我想添加 20 个示例按钮时则不行。
例如,假设我点击了 1 个样本按钮 5 次,但现在我点击了 20 个样本按钮,我希望计数器 x() 现在显示 25,而 y() 应该有 26 个元素(我开始NA 在第一个元素位置)。
是否有可能以某种方式与observeEvent() 发生非此即彼的反应?
【问题讨论】:
标签: r shiny r-markdown