after clicking the bottom run own function within shiny

Viewed 108

I would like to write a Gui and Server, using Shiny, so that an integer is read and after clicking the bottom my function should be called and the output should appear in dashboard (shiny-GUI)

if (interactive()) {

  ui <- fluidPage(
    numericInput("obs", "your number:", 10, min = 1),
    actionButton("do", "Print the Result")
  )
  # my function
  calculate<-function(x){y<-x*x
  if(y<24){print("the value is less than 5")}
  else 
  {print("the value is greater than 5")}
  }
  # server
  server <- function(input, output, session) {
    observeEvent(input$do, {
      output$value <- renderText({ input$calculate(obs) })
    })
  }
  # call server
  shinyApp(ui, server)
}

I just tried it in a simple example, however the code dose not work! How can one call a function in server by clicking an action bottom generally?

1 Answers

You want to make your server something like this

server <- function(input, output, session) {
reactiveText <- eventReactive({
  input$do
},{
  calculate(input$obs)
})
output$value <- renderText({reactiveText() })
}

in general you want to go at like this (event)Reactive is for output to renders and are lazy evaluated. Which means they are only evaluated once the object is shown in the UI

Observe(Event) are eager evaluated, which means the are evaluated immediately when dependent variables are changed. The are good for updateInput, showModal or other changes to the UI that you want to happen immediately.

You don't want to put any assignment to output inside any reactive or observe functions.

But of course once you master it all - rules are there to be broken ;-)

PS

to see the result of cour code you need to add an output Objekt to your UI like this

ui <- fluidPage(
  numericInput("obs", "your number:", 10, min = 1),
  actionButton("do", "Print the Result"),
  textOutput("value")
)
Related