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

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

Additional question: how do I call the functions defined in abc.R from the R / command prompt?

+51
scope file namespaces r user-defined-functions
Nov 25 '12 at 4:25
source share
1 answer

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

If abc.R:

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

and 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:

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

and xyz.R is:

 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 > 
+84
Nov 25 '12 at 10:57
source share



All Articles