Open In App

How to use the source Function in R

Last Updated : 28 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be looking at the practical implementation of the source function in the R programming language.

Source Function:

Source function in R is used to use functions that are created in another R script. The syntax of this function is given below:

source(“Users/harsh/Desktop/GeeksforGeeks/gfg.R”)

All we are required is to put the above line at the top of the script in which we want to use a function of the gfg.R file.

Advantages of the source function:

  • Source function increases the reusability of the code. Once written then we can use the same code in any script.
  • Helpful in handling big projects.
  • Tasks can be completed in lesser time.

Example: 

Let’s consider that we have an R script that contains two simple functions add() and subtract(). add() function takes two numbers as input and displays the result of the same. subtract() function on the other hand also takes two numbers as input and displays the output of the same.

R




# gfg.R
  
# Define a function that 
# adds two number and return the same
add <- function(number1, number2) {
  return(number1 + number2)
}
  
# Define a function that 
# subtracts two number and return the same
subtract <- function(number1, number2) {
  return(number1 - number2)
}


Now consider that we are using main.R script and within that script, we want to use add and subtract functions that are defined under gfg.R script. So, we can use the statement source(“gfg.R”) at the top of the script main.R in order to use these functions. 

Note: Here, main.R script and gfg.R script resides in the same folder. If we want to use some other R script then the full path of the file must be given.

Here, we are creating a main.R script and here at the start of this script we are using the source function passed as the parameter gfg.R to use the functions from the gfg.R file within the main.R file.

R




# main.R
  
# Source function
source("gfg.R")
  
# Defining variables
number1 = 10
number2 = 20
  
# Calling add() function defined under gfg.R file
add(number1, number2)
  
# Calling subtract() function defined under gfg.R file
subtract(number1, number2)


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads