G S*_*hah 87 scope namespaces r file user-defined-functions
如何调用另一个文件中abc.R文件中定义的功能,说xyz.R?
甲补充问题是,如何调用从R提示/命令行中abc.R定义的函数?
A_K*_*A_K 125
您可以调用source("abc.R")
后跟source("xyz.R")
(假设这两个文件都在您当前的工作目录中).
如果abc.R是:
fooABC <- function(x) {
k <- x+1
return(k)
}
Run Code Online (Sandbox Code Playgroud)
和xyz.R是:
fooXYZ <- function(x) {
k <- fooABC(x)+1
return(k)
}
Run Code Online (Sandbox Code Playgroud)
然后这将工作:
> source("abc.R")
> source("xyz.R")
> fooXYZ(3)
[1] 5
>
Run Code Online (Sandbox Code Playgroud)
即使存在周期性依赖关系,这也会有效.
例如,如果abc.R是这样的:
fooABC <- function(x) {
k <- barXYZ(x)+1
return(k)
}
barABC <- function(x){
k <- x+30
return(k)
}
Run Code Online (Sandbox Code Playgroud)
和xyz.R是这样的:
fooXYZ <- function(x) {
k <- fooABC(x)+1
return(k)
}
barXYZ <- function(x){
k <- barABC(x)+20
return(k)
}
Run Code Online (Sandbox Code Playgroud)
然后,
> source("abc.R")
> source("xyz.R")
> fooXYZ(3)
[1] 55
>
Run Code Online (Sandbox Code Playgroud)