Reputation: 14192
I have this small example of what I'm trying to do:
I am generating a normal distribution of data sims
which changes based on which button is pressed. The first 5 values are printed in the first output box. From this, we collect samples of data and calculate the mean of each sample - samp_sims
. As the slider is moved, the sample size changes and so do the mean -visible in the second output box.
It is ok that the population values sims
don't change when the slider moves. However, if a user is then to click "optionA" after "optionB", the population sims
numbers change - but the sample mean numbers (output 2 at the bottom) do not update - they are still from the previous option. They don't update until the slider is moved again. I would like them to also automatically update when the button is pressed. I tried doing this using an observeEvent()
action - putting the same code for my eventReactive()
event inside, but this didn't work.
Is there a way to ensure that the samp_sims
values update whenever the slider moves or a button is pressed?
---
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]})
```
Upvotes: 0
Views: 214
Reputation: 21297
You should try a list()
of two events for eventReactive
. In your case,
samp_sims <- eventReactive(list(input$sampsize,input$go) , {
apply(replicate(100, sample(sims(), input$sampsize, T)),2,mean)
})
A working example is below
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)
Upvotes: 1