簡體   English   中英

在循環中使用source()來自動加載我的函數?

[英]Using source() in a loop to automatically load up my functions?

我有大約30個研究項目的功能,不想打字

source(paste("C:/functions","/function1.txt",sep=""))

30次C:/functions是我的函數目錄,而/function1.txt是一個特殊的函數。

我試過了

files <- list.files("C:/functions")
sapply(1:length(files),source(paste("C:/functions/",files[i],sep="")))

它不起作用。 錯誤消息: Error in match.fun(FUN) : c("'source(paste(\\"C:/functions/\\", ' is not a function, character or symbol", "' files[i], sep = \\"\\"), TRUE)' is not a function, character or symbol")

我也用for循環嘗試了它,它不起作用。

如果你有許多函數的集合,你也可以創建一個R包。 好處:

  • 將文檔與函數一起包含在內的好方法,尤其是在使用roxygen2時
  • 將代碼分發給其他人的簡便方法。
  • 測試可以包含在源代碼中。
  • 使用library輕松加載所有功能。
  • 僅向用戶公開頂級功能的能力,將低級別功能僅供內部使用。

有關更多詳細信息,請參閱編寫R擴展

seancarmody的回答略有變化:

files <- list.files("C:/functions",full.names=TRUE,pattern="\\.txt")
sapply(files, source)

?source幫助中給出了一些用於獲取文件目錄的R代碼。 尤其是:

## If you want to source() a bunch of files, something like
## the following may be useful:
sourceDir <- function(path, trace = TRUE, ...) {
    for (nm in list.files(path, pattern = "\\.[RrSsQq]$")) {
        if(trace) cat(nm,":")           
        source(file.path(path, nm), ...)
        if(trace) cat("\n")
     }
}

要調用該函數,只需要:

sourceDir("C:/function")

您可以隨時將該功能放入Rprofile中。


一個小問題,你的文件擴展名為.txt ,這意味着你可以在上面的函數中將模式匹配器更改為:

pattern = "\\.txt$"
files <- list.files("C:/functions")
sapply(files, function(x) source(paste0("C:/functions/", x)))

請注意, sapply需要一個函數作為第二個參數。

也許你會喜歡這個......

install.packages('R.utils')
library(R.utils)
sourceDirectory( 'C:/functions', '*.txt' )

有關采購的好處,請參閱?sourceDirectory ...

Arguments

path    
A path to a directory to be sourced.

pattern 
A regular expression file name pattern to identify source code files.

recursive   
If TRUE, subdirectories are recursively sourced first, otherwise not.

envir   
An environment in which the code should be evaluated.

onError 
If an error occures, the error may stop the job, give a warning, or silently be skipped.

verbose 
A logical or a Verbose object.

... 
Additional arguments passed to sourceTo().

擺脫“每個文件一個函數”的Matlab范例並沒有什么壞處。 您可以將所有函數放入單個my_research_functions.R文件中,然后執行source('C:/functions/my_research_functions.R')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM