对于R闪亮应用程序中的许多输出变量,如何对输入变量执行相同的计算?

时间:2021-02-04 03:11:27

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:

我有一个带有一个滑块输入和两个文本输出的shinyApp。应用程序对输入进行一些计算,并在静态文本字段中返回输出。这是我目前的代码:

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:

代码是无效的,因为它执行相同的计算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.)

我需要更改代码才能使其工作? (提前致谢。)

1 个解决方案

#1


0  

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

对于R闪亮应用程序中的许多输出变量,如何对输入变量执行相同的计算?

#1


0  

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

对于R闪亮应用程序中的许多输出变量,如何对输入变量执行相同的计算?