Gustavo B Paterno
Gustavo B Paterno

Reputation: 986

Refresh input values in shiny app with `actionButton`

I am working on a shiny aplication to explore sums of squares in linear regression (link). This application has three sliderInput, so the user can choose: (i) the regression slope; (ii) the sample size and (iii) the standard deviation. With this inputs, the app generate a raw dataset to plot some graphs. This is working fine with the reactive function. Any change in one parameter will generate new data. My problem is that I want to include a buttom to "refresh" all values, actually to re-run the functions that generate these parameters.

So my question is how do I include this in the server?

I know I have to include the buttom in the ui:

actionButton(inputId = "refresh", label = "Refresh" , 
             icon = icon("fa fa-refresh"))
)

But I dont know how to use this buttom to rerun the reactive functions that generate the data. This is the code that generates the data in the server:

### Saving data:
Rawdata <- reactive({
  slope <- input$slope
  SD <- input$SD
  sample <- input$sample
  x <- round(1:sample + rnorm(n = sample, mean = 1, sd = 1), digits = 2)
  y <- round(slope * (x) + rnorm(n = sample, mean = 3, sd = SD ), digits     = 2)
  mod <- lm(y ~ x, data.frame(y,x))
  ypred <- predict(mod)
  Rawdata <- data.frame(y, x, ypred)
})

The full source code is available in github: ui | server

I appreciate any suggestion.

Best wishes, Gustavo

Upvotes: 1

Views: 3845

Answers (1)

zero323
zero323

Reputation: 330063

You can isolate other input variables and make actionButton only dependency for reactive expression:

library(shiny)

shinyApp(
  server = function(input, output, session) {
      rawdata <- reactive({
        # Make action button dependency
        input$refresh 
        # but isolate input$sample
        isolate(rnorm(input$sample))
      })

      output$mean <- renderText({ mean(rawdata()) })
  },
  ui = fluidPage(
    actionButton(inputId = "refresh",
      label = "Refresh", icon = icon("fa fa-refresh")),
    sliderInput(inputId = "sample",
      label = "Sample size",
      value = 50, min = 10, max = 100),
    textOutput("mean")
  )
)

Upvotes: 3

Related Questions