1

I'm new to shiny and trying to accomplish rather a simple task using an action button:

  • User clicks a button and a function is called
  • This function does some calculations using input variables and updates/creates several global variables (reactiveValues, probably inside an observe block?)
  • I'd like to display those values back on the UI (using render* function)
  • Whenever user changes input values, the UI is automatically updated

Relevant code bits are:

server.R

...
rv <- reactiveValues() 
observe({
 if(input$run){
  rv$a <- someFunc(input$aa)
 }
})
output$msg = renderText({ rv$a })
...

ui.R

...
selectInput("aa", ...)
...
actionButton("run", "Run")
...
textOutput("msg")

How can I change msg based on the input aa each time user clicks the button?

Mike Wise
  • 22,131
  • 8
  • 81
  • 104
xeroqu
  • 425
  • 5
  • 14
  • 1
    The `...`s in the code aren't very helpful. Try to make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Describe exactly what you want to change the `msg` value to and how `aa` is involved. I don't really see what the problem is here. What exactly is the behavior you are observing now. – MrFlick Apr 05 '17 at 15:14
  • As far as the code is specified above the renderText already changes the 'msg' in UI.r. Do you want to change the actual wording of the `textOutput` based on the input? – timfaber Apr 05 '17 at 15:21
  • Any feedback for me? – Mike Wise Apr 06 '17 at 09:47
  • @MrFlick Yes, I know, but my code is quite complicated and cannot be reproduced just like that. I appreciate your comment. – xeroqu Apr 06 '17 at 14:20

1 Answers1

4

I am not convinced I understood what you want, but I imagine it to be something like this:

library(shiny)
u <- fluidPage(
  titlePanel("Simple Selectable Reactive Function"),
    sidebarLayout(
      sidebarPanel(
        sliderInput("vv", "Choose a value",min=-3.14,max=3.14,value=0),
        selectInput("aa", "Choose a function", choices=c("sin","cos","exp")),
        actionButton("run", "Change Function and Run")
      ),
     mainPanel(
      h2("Results"),
      verbatimTextOutput("msg")
 )))
s <- function(input,output){

  rv <- reactiveValues(func=NULL) 

  observeEvent(input$run,{   rv$func <- input$aa })

  funcval <- reactive({
    v <- 0
    if (rv$func=="sin") v <- sin(input$vv)
    if (rv$func=="cos") v <- cos(input$vv)
    if (rv$func=="exp") v <- exp(input$vv)
    v
  })
  output$msg = renderPrint({
       if (is.null(rv$func)) return("not running")
       fv <- funcval()
       sprintf("%s(%.3f)=%.3f",rv$func,input$vv,fv)
    })
}
shinyApp(ui=u,server=s)

Yielding this:

enter image description here

Note that the slider input value formats its current value rather badly when the min and max values are not even. Not sure what one can do about this.

Mike Wise
  • 22,131
  • 8
  • 81
  • 104