6

我有大约 30 个研究项目的功能,不想打字

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

30 次 whereC:/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循环尝试过,它不起作用。

4

6 回答 6

10

如果你有这么多函数的集合,你也可以创建一个 R 包。优点:

  • 在函数旁边包含文档的好方法,尤其是在使用roxygen2时。
  • 将代码分发给其他人的简单方法。
  • 测试可以包含在源代码中。
  • 使用 . 轻松加载所有功能library
  • 仅向用户公开顶级功能的能力,仅将低级功能留作内部使用。

有关更多详细信息,请参阅编写 R 扩展

于 2012-08-29T12:16:25.713 回答
7

seacarmody 的回答略有变化:

files <- list.files("C:/functions",full.names=TRUE,pattern="\\.txt")
sapply(files, source)
于 2012-08-29T12:08:14.043 回答
6

帮助中提供了一些用于获取文件目录的 R 代码?source。尤其是:

## 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$"
于 2012-08-29T12:04:43.343 回答
5
files <- list.files("C:/functions")
sapply(files, function(x) source(paste0("C:/functions/", x)))

Note that sapply requires a function as the second argument.

于 2012-08-29T12:06:35.060 回答
2

也许你会喜欢这个...

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().
于 2012-08-30T05:05:45.557 回答
1

摆脱“每个文件一个函数”的 Matlab 范式并没有什么坏处。您可以将所有功能放入一个my_research_functions.R 文件中,然后执行source('C:/functions/my_research_functions.R')

于 2012-08-29T12:17:05.587 回答