[英]How do I perform the same calculation on an input variable for many output variables in an R shiny app?
Situation 情况
I have a shinyApp with one slider input and two text outputs. 我有一个带有一个滑块输入和两个文本输出的ShinyApp。 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.)
(提前致谢。)
We can place that inside reactive
我们可以将其放置在
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 - 输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.