简体   繁体   English

在一个.R文件中定义所有函数,从另一个.R文件中调用它们。如果可能的话怎么样?

[英]Define all functions in one .R file, call them from another .R file. How, if possible?

How do I call functions defined in abc.R file in another file, say xyz.R? 如何在另一个文件中调用abc.R文件中定义的函数,比如xyz.R?

A supplementary question is, how do I call functions defined in abc.R from the R prompt/command line? 补充问题是,如何从R提示符/命令行调用abc.R中定义的函数?

You can call source("abc.R") followed by source("xyz.R") (assuming that both these files are in your current working directory. 你可以调用source("abc.R")其次是source("xyz.R")假定这两个文件都在你的当前工作目录。

If abc.R is: 如果abc.R是:

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

and xyz.R is: 和xyz.R是:

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

then this will work: 然后这将工作:

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

Even if there are cyclical dependencies, this will work. 即使存在周期性依赖关系,这也会有效。

Eg If abc.R is this: 例如,如果abc.R是这样的:

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

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

and xyz.R is this: 和xyz.R是这样的:

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

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

then, 然后,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从字符串中提取一个或多个单词并在 R 中的另一个文件的两个不同列中搜索它们 - How to extract one or more words from a string and search for them in two different columns form another file in R 如何从R中的不同函数一个接一个地写入csv文件中的数据? - How to write data in a csv file from different functions in R one after another? R:来自另一个文件的DeployR访问功能 - R: DeployR access functions from another file 如何列出 R 文件中的所有函数签名? - How to list all the functions signatures in an R file? 有没有办法从 R 中的另一个文件调用变量而不让它们出现在工作区中? - Is there a way to call variables from another file in R without having them appear in the workspace? 对于许多文件,如何在 R 中将列从一个文件合并到另一个文件? - How to merge columns from one file to another in R for many files? 是否可以在R Markdown文件中将标题定义为标题? - Is it possible to define the title in an R Markdown file as a header? 从R中的文件名定义文件路径 - Define the file path from the file name in R R函数包含在另一个文件中时需要包声明吗? - R Functions require package declaration when they are included from another file? 如何区分二元组并将其合并到R Studio中的一个CSV文件中 - How to distinguish bigrams and merge them into one CSV file in R Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM