[英]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
循環嘗試了它,它不起作用。
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.