【问题标题】:Shiny reactive expression call to local function对本地函数的闪亮反应表达式调用
【发布时间】:2015-10-16 22:59:57
【问题描述】:

使用 Shiny 构建应用程序时,我遇到了 reactive 调用本地定义函数的问题。 一个仿真例子:

  <server.R>
  shinyServer(function(input, output) { 
  myfunc <- function(x) x+1
  myreac <- reactive({
          y <- myfunc(input$var)
          y
  })  
  # print y value test
  output$text <- renderText({ 
  myreac <- myreac()
  paste("This is your output:",myreac)
  })  

闪亮的用户界面

  shinyUI(fluidPage(
  titlePanel("New App"),  
  sidebarLayout(
  sidebarPanel(
  helpText("My App"),      
  selectInput("var", 
              label = "Choose an option:",
              choices = list("1", "2",
                             "3"),
              selected = "1"),
      ),

mainPanel(
  textOutput("text"),
  )   
 )
))  

我得到的输出:基本上是空白的:

This is your output:

似乎反应式没有任何输出。我将不胜感激。

【问题讨论】:

    标签: r function shiny


    【解决方案1】:

    有几个额外的逗号,但除此之外,如果您将 x 转换为数字,它应该可以工作,

    library(shiny)
    shinyApp(
        shinyUI(fluidPage(
            titlePanel("New App"),  
            sidebarLayout(
                sidebarPanel(
                    helpText("My App"),      
                    selectInput("var", 
                                label = "Choose an option:",
                                choices = list("1", "2", "3"),
                                selected = "1")
                ),
                mainPanel(
                    textOutput("text")
                )
            )
        )),
        shinyServer(function(input, output) { 
            myfunc <- function(x) as.numeric(x)+1
            myreac <- reactive({
                y <- myfunc(input$var)
                y
            })
    
            ## print y value test
            output$text <- renderText({ 
                myreac <- myreac()
                paste("This is your output:", myreac)
            })
        })
    )
    

    【讨论】:

    • @bunk:准点。在原始代码中,选择是字符,只是认为没有对类的隐含假设,因此必须使用quote。我遇到的下一个问题是所有选择都是同时评估的……有什么理由吗?
    • 我不确定你的意思。你看到输出了吗?
    • 是的,输出同时打印所有三个选项。在上面的示例中,This is your output: 2, This is your output: 3, This is your output: 4 尽管 selectInput 设置为 1(在用户界面上)。
    • 您在复制和粘贴上述内容时得到了?我一次只能看到一个输出
    • 在实际代码中获取它。我在myfunc 中使用了一个grep,它确实抱怨pattern has length &gt; 1... 作为警告消息。似乎所有 3 个“选择”都会同时得到评估?
    猜你喜欢
    • 2022-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多