Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

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

1 Answer

0 votes
by
edited by

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

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...