Reputation: 592
Situation
I have a shinyApp with one slider input and two text outputs. The App does some calculation on the input and returns the output in static text fields. Here is my current code:
library(shiny)
ui=fluidPage(
sliderInput("slider", "Slide Me", 0, 100,1),
textOutput("result01"),
textOutput("result02")
)
server=function(input,output){
output$result01=renderText({
MYVARIABLE=(input$slider)^12
MYVARIABLE+34543
})
output$result02=renderText({
MYVARIABLE=(input$slider)^12
MYVARIABLE+67544
})
}
shinyApp(ui, server)
Problem
The code is inefficent, because it does the same calculation TWICE:
MYVARIABLE=(input$slider)^12
This is okay for the moment, because the calculation is not terribly complicated and because I only have two outputs. In the future however, I want to do a more complicated calculation for many more outputs at the same time.
Wish
To only do the same calculation once and not multiple times, I would like to do something like this on the server side:
server=function(input,output){
MYVARIABLE=(input$slider)^12
output$result01=renderText({
MYVARIABLE+34543
})
output$result02=renderText({
MYVARIABLE+67544
})
}
However, this gives the following error message:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
Question
What do I need to change my code to, to make this work? (Thanks in advance.)
Upvotes: 2
Views: 187
Reputation: 887661
We can place that inside reactive
library(shiny)
options(scipen = 999)
ui <- fluidPage(
sliderInput("slider", "Slide Me", 0, 100,1),
textOutput("result01"),
textOutput("result02")
)
server <- function(input,output){
MYVARIABLE <- reactive({(input$slider)^12})
output$result01 <- renderText({
MYVARIABLE()+34543
})
output$result02 <- renderText({
MYVARIABLE()+67544
})
}
shinyApp(ui, server)
-output
Upvotes: 0