簡體   English   中英

在一個.R文件中定義所有函數,從另一個.R文件中調用它們。如果可能的話怎么樣?

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

如何在另一個文件中調用abc.R文件中定義的函數,比如xyz.R?

補充問題是,如何從R提示符/命令行調用abc.R中定義的函數?

你可以調用source("abc.R")其次是source("xyz.R")假定這兩個文件都在你的當前工作目錄。

如果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
> 

即使存在周期性依賴關系,這也會有效。

例如,如果abc.R是這樣的:

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

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

和xyz.R是這樣的:

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
>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM