How to Write Functions in R Programming Language

Writing functions in R language is very simple and much like any other programming language. A function is a set of instructions coupled together to perform a specific task. In R there are inbuilt functions like mean(), sum() etc. and users can also create their functions on their own.

Learn to Write Functions in R

Tutorial to write first function in R Programming

For the demo purpose I am going to create 2 different types of functions namely:

  • Sum(i,y) function to calculate sum of two numbers
  • Cube(x) function to calculate cube of number ‘x’ and I will use return statement to return the answer.

First to create a function in R language go through the following points:

  • To create a function in R keyword to be used is “function()”
  • Arguments are optional and can be passed as “function(arg1, arg2,….)”
  • Return statement is used in the end of function body.

Writing first Function in R:

Now you can create the function in console of R or you can create the function in R script file. I prefer to use the script approach as it helps me in using the function again by calling the script file.

Create new R script file as shown below:

How to Write Functions in R Programming Language

Type the following code in the window and save the file

How to Write Functions in R Programming Language-1

Since I am using the Script approach of creating R function, I have to use the source command in the console part. Here function1.R is the name of the script file I created in the above step.

How to Write Functions in R Programming Language-2

To call the function type function name and pass the arguments if needed. In this example I am calling Sum(4,5) function.

How to Write Functions in R Programming Language-3

In this function I have not used the return statement. Now let’s look at the function with return statement.

How to Write Functions in R Programming Language-4

Let’s run this on console and see the result

How to Write Functions in R Programming Language-5

Thank you for reading the post. Subscribe Technokarak.com for more Programming Tutorials.

Leave a Reply