繁体   English   中英

R+shiny:从非反应性 function 读取输入变量

[英]R+shiny: Read an input variable from a non-reactive function

我有以下代码:

library(shiny)

foo <- function(a, b){
  a*b*input$ni
}

ui <- fluidPage(
  numericInput("ni", label = "in", value = 3),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  output$out <- renderText(foo(a = 2, b = 4))
}

shinyApp(ui = ui, server = server)

运行这个会导致错误object 'input' not found The foo function does not know about the shiny inputs because it's written outside the shiny functions and it's not a reactive function.

我怎样才能让它工作? 由于我的代码是如何构建的(除了这个 MWE),我需要 function foo只接受参数ab而没有其他参数。 也就是说,输入不能作为参数传递给它。 它还需要位于服务器 function 之外。

有没有办法让它以某种方式从 shiny 环境中获取输入变量?

If you can't change the function arguments you can make use of global assignment operator ( <<- ) so that the variable is available outside the scope of function.

library(shiny)

foo <- function(a, b){
  a*b*ni
}

ui <- fluidPage(
  numericInput("ni", label = "in", value = 3),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  
  output$out <- renderText({
    ni <<- input$ni
    foo(a = 2, b = 4)
  })
}

shinyApp(ui = ui, server = server)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM