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

后端 未结 1 2044
孤独总比滥情好
孤独总比滥情好 2020-12-12 12:38

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

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

相关标签:
1条回答
  • 2020-12-12 12:46

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

    If abc.R is:

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

    and xyz.R is:

    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.

    E.g. If abc.R is this:

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

    and xyz.R is this:

    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
    >
    
    0 讨论(0)
提交回复
热议问题