2015-10-23 32 views
0

我想將我的應用程序拆分成更小的和平以獲得更好的處理。無源內容中的來源Shiny

server.R

library(shiny) 
source("onLoad.R", local = TRUE) 

    shinyServer(function(input, output, session) { 

    sourceRecursive("/.../") 

}) 

sourceRecursive

#check folder and all subfolders for .R files 
#source() them! 
sourceRecursive <- function(path) { 
     dirs <- list.dirs() 
     files <- dir(pattern = "^.*[Rr]$", include.dirs = FALSE) 
     for (f in files) 
      source(f) 
     for (d in dirs) 
      sourceRecursive(d) 
} 

示例文件我嘗試源。 file.R

output$myChoices <- renderUI({ 
    selectInput(inputId = 'x', 
      label = 'y', 
      choices = levels(myDataSet$df$z), 
      multiple = T 
    ) 
}) 

反彈有:在輸出$ myChoices

錯誤< - renderUI({: 對象 '輸出' 未找到

顯然的問題是,在file.R變量output未定義,因爲這是一個變量,在閃亮的上下文中使用。我怎麼會告訴R(或閃亮)將所有變量視爲閃亮定義的變量(如output$whatever,input$something,reactive等)。這對我來說很重要,爲了把這個計劃分解成更小的和平。

+0

沒有你的答案,但你可以在你的file.R中有'x < - renderUI({...})',然後使用在服務器中輸出$ mychoices < - x' – Chris

回答

0

如果您在撥打電話時使用local=TRUE,前提是sourceRecursive位於正確範圍(可能放在server.R中)會怎麼樣。看到這個文檔here

0

我用兩個源(本地= TRUE)和sys.source以將文件加載到適當的環境,似乎工作:

library(shiny) 
shinyServer(function(input, output, session) { 
    # From http://shiny.rstudio.com/articles/scoping.html 
    output$text <- renderText({ 
     source('each_call.R', local=TRUE) 
    }) 

    # Source in the file.R from the example in the question 
    sys.source('file.R', envir=environment()) 
}) 

我沒有測試,但你也許可以使用:

sourceRecursive <- function(path, env) { 
    files <- list.files(path = path, pattern = "^.*[Rr]$", recursive = TRUE) 
    for (f in files) sys.source(f, env) 
} 

shinyServer(function(input, output, session) { 
    session.env <- environment() 
    sourceRecursive(path = ".", env = session.env) 
})