在一个 .R 文件中定义所有函数,从另一个 .R 文件调用它们.如果可能,如何? [英] Define all functions in one .R file, call them from another .R file. How, if possible?

查看:20
本文介绍了在一个 .R 文件中定义所有函数,从另一个 .R 文件调用它们.如果可能,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在另一个文件中调用定义在 abc.R 文件中的函数,比如 xyz.R?

How do I call functions defined in abc.R file in another file, say xyz.R?

补充问题是,如何从 R 提示符/命令行调用 abc.R 中定义的函数?

A supplementary question is, how do I call functions defined in abc.R from the R prompt/command line?

推荐答案

您可以调用 source("abc.R") 后跟 source("xyz.R")(假设这两个文件都在您当前的工作目录中.

You can call source("abc.R") followed by source("xyz.R") (assuming that both these files are in your current working directory.

如果 abc.R 是:

If abc.R is:

fooABC <- function(x) {
    k <- x+1
    return(k)
}

和 xyz.R 是:

fooXYZ <- function(x) {
    k <- fooABC(x)+1
    return(k)
}

那么这将起作用:

> source("abc.R")
> source("xyz.R")
> fooXYZ(3)
[1] 5
> 

即使存在循环依赖,这也行得通.

Even if there are cyclical dependencies, this will work.

例如如果 abc.R 是这个:

E.g. If abc.R is this:

fooABC <- function(x) {
    k <- barXYZ(x)+1
    return(k)
}

barABC <- function(x){
    k <- x+30
    return(k)
}

和 xyz.R 是这样的:

and xyz.R is this:

fooXYZ <- function(x) {
    k <- fooABC(x)+1
    return(k)
}

barXYZ <- function(x){
    k <- barABC(x)+20
    return(k)
}

那么,

> source("abc.R")
> source("xyz.R")
> fooXYZ(3) 
[1] 55
>

这篇关于在一个 .R 文件中定义所有函数,从另一个 .R 文件调用它们.如果可能,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆