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

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

问题描述

如何在另一个文件(例如xyz.R)中调用abc.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为:

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天全站免登陆