【问题标题】:Call function and save return list in Shiny在 Shiny 中调用函数并保存返回列表
【发布时间】:2017-01-02 17:51:50
【问题描述】:

我正在尝试调用 server.R 中的函数并将返回的列表保存到全局环境中,该函数由操作按钮调用。然后,我将使用该列表运行另一个函数,该函数由另一个按钮触发,基于该列表,以绘制图形。这是一个简单的示例代码:

shinyServer(function(input, output) {

  v <- reactiveValues()

  observeEvent(input$button1, {
    v$button1 = TRUE
  })

  savedlist <<- reactive({
    if (v$button1){
      return(savedlist <- f1(10)
    }
  })

 output$plot <- renderPlot({
   f2(savedlist)
 })

})

在哪里

f1 <- function(x){
  savedlist = list(xdata = 1:x, ydata = x:1)
  names(savedlist) = c("xdata", "ydata")
  return(savedlist)
}

f2 <- function(x){
  attach(savedlist)
  plot(xdata, ydata)
}

但我无法让它工作......

谢谢。

【问题讨论】:

  • 试试observe({if (v$button1){ savedlist &lt;&lt;- f1(10) }})
  • 感谢您的回复。它给了我错误:Warning: Error in if: argument is of length zero
  • 尝试添加默认值v &lt;- reactiveValues(button1=FALSE)
  • 再次感谢您。现在没有错误,但是当我单击按钮时,什么也没有发生。运行该功能大约需要一分钟。我怎么知道它正在运行?我已经实现了this(正在加载...信号),当我按下按钮时它没有加载。

标签: r shiny


【解决方案1】:

试试这个

library(shiny)
ui=shinyUI(fluidPage(

  actionButton("button1","button1"),
  plotOutput("plot")

))
f1 <- function(x){
  savedlist = list(xdata = 1:x, ydata = x:1)
  names(savedlist) = c("xdata", "ydata")
  return(savedlist)
}
f2 <- function(x){ # change a bit to use x as argument
  plot(x$xdata, x$ydata)
}

server=shinyServer(function(input, output) {

  v <- reactiveValues(button1=FALSE)

  observeEvent(input$button1, {
    v$button1 = TRUE
  })

  observe({
    if (v$button1){
      savedlist <<- f1(10)
    }
  })

      output$plot <- renderPlot({
        if(v$button1){# plot only after button because before list dont exist
        f2(savedlist)
        }
      })

})

shinyApp(ui,server)

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2016-07-30
    • 1970-01-01
    • 2021-04-28
    • 2023-03-21
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多