0 votes
1 view
in R Programming by (5.2k points)

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

1 Answer

0 votes
by (25.3k points)

To use functions defined in one .R file from another .R file, you can call the source("abc.R") followed by source("xyz.R") (assuming that both these files are in your current working directory.

For instance:

If abc.R is:

funABC <- function(x) {

  y <- x^2

  return(y)

}

And xyz.R is:

funXYZ <- function(x) {

  y <- funABC(x)+ x^2

  return(y)

}

Then the following code will work:

source("abc.R")

> source("xyz.R")

> funXYZ(3)

[1] 18

This method works even if a cyclical dependency exists.i.e.,

If abc.R is this:

funABC <- function(x) {

    y <- barXYZ(x)+1

    return(y)

  }

barABC <- function(x){

  y <- x+30

  return(y)

}

And xyz.R is this:

funXYZ <- function(x) {

    y <- funABC(x)+1

    return(y)

  }

barXYZ <- function(x){

  y<- barABC(x)+20

  return(y)

}

Then:

source("abc.R")

source("xyz.R")

funXYZ(3) 

[1] 55

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...