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?
You can use the source function in R to reuse functions that you create in another R script. This function uses the following basic syntax: source("path/to/some/file.R") Simply add this line to the top of your R script and you'll be able to use any functions defined in file.
There are two ways to create an R file in R studio: You can click on the File tab, from there when you click it will give a drop-down menu, where you can select the new file and then R script, so that, you will get a new file open.
The R and RStudio programs are typically used to open R files since they provide helpful IDE tools. You can also use a plain text editor to view the contents of an R script.
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 >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With