将对象传递给闪亮的应用程序并使用runApp启动

时间:2016-07-12 18:32:03

标签: r scope shiny

我正在创建一个包含一些交互式闪亮应用的包。这些应用程序的目的是促进对内存中对象的GUI探索。例如,我有一个由离散变量组成的对象,我想传递给闪亮的应用程序,然后通过GUI界面进行调整。

但是,当我试图从Shiny App访问这个内存中对象时,我遇到了麻烦。

以下是相关代码:

首先,我将shinyServer函数包装在另一个函数中。我的想法是让闪亮的服务器访问传递的对象。

    #' @export
    appServer <- function(bins) {
      su <- summary(bins)
      shinyServer(function(input, output) {

        ## values that should trigger updates when changed
        values <- reactiveValues(summary=su, i=1, bins=bins)

    # excluded rest of body for brevity ...

    }

在这个函数中,我创建一个shinyApp对象并传入ui(在另一个文件中)和上面定义的appServer函数的结果。

makeApp <- function(bins) {
  shiny::shinyApp(
    ui = appUI,
    server = appServer(bins))
}

在此函数中调用上述函数,该函数将对runApp的调用包装起来并从用户处获取参数。

#' @export
adjust <- function(bins) {
  ## access data from the app?

  app <- makeApp(bins)
  shiny::runApp(app)
}

如何将内存中对象传递给从另一个包导入的shinyApp?

当我执行上面的代码时,收到以下错误:

  

错误:path [1] =“C:\ Users \ myusername \ AppData \ Local \ Temp \ RtmpWMpvHT \ widgetbinding23e8333e5298”:系统找不到指定的路径

1 个答案:

答案 0 :(得分:5)

在下面的示例中,我将演示如何将对象x从全局环境或任何其他环境传递到闪亮的应用程序并更改其值。我不确定这是否能回答你的问题。无论如何它可能证明是有用的:)

library(shiny)

x <- 5
x
deparse(substitute(x)) # is going to do the trick

fun <- function(obj) {

  # get the name of the passed object
  object_to_change <- deparse(substitute(obj)) 

  # get the object from a given environment
  val <- get(object_to_change, envir = .GlobalEnv) 
  # ?environment

  # Save the object as a reactive value
  values <- reactiveValues(x = val)                                   

  # Now define the app that is going to change the value of x
  ui <- shinyUI(fluidPage(
    br(),
    actionButton("quit", "Apply changes and quit"),
    textInput("new", "", value = NULL, placeholder = "Set new value of x"),
    textOutput("out")
  ))

  server <- function(input, output) {

    output$out <- renderPrint({ 
      values$x        
    })

    # change the value of x
    observe({
      req(input$new)
      values$x <- as.numeric(input$new)
    })

    # Apply changes and quit     
    observe({
      if (input$quit == 1) {
        assign(x = object_to_change, value = values$x, envir = .GlobalEnv)
        stopApp()
      } 
    })
  }
  # Run the app  
  shiny::shinyApp(ui, server)
}

fun(x)

# Check the new value of x in the .GlobalEnv
x
相关问题