131

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/command line?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
G Shah
  • 2,045
  • 2
  • 16
  • 17

1 Answers1

184

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
>
A_K
  • 2,581
  • 2
  • 14
  • 10
  • 14
    A nuance: you only have to `source` a file/function once. Then it is in your workspace and you can use it at any time. If you change it, you have to re-source it. If your functions are changing a lot since you are converting the code, put them all in one file and just source the whole thing every time. You could also have a separate smaller file that 1. sources the larger collection of functions and 2. Runs your test cases. In R there are lots of ways to arrange your work flow. – Bryan Hanson Nov 25 '12 at 13:01
  • 5
    Thanks for the nuance, Bryan. I was demonstrating this as 2 scenarios that most people from procedural languages might wonder about. It is as if the files were edited to add the cyclic dependency, in which case they need to be resourced (as shown) & the cycles don't affect the sourcing of the files. – A_K Nov 25 '12 at 13:25
  • Thank you both of you. @A_K: thanks a lot for highlighting the cyclic dependency issue. Saved me some hours of digging through the "can-be-improved" R documentation :) – G Shah Nov 25 '12 at 15:51
  • 2
    I am new to learning R after retirement. This is marvellous! – Unnikrishnan Dec 23 '20 at 12:10