CodeInfoNet

Learn programming on the go!

Home » Functions in R programming

Functions in R programming

functions in R
What is function in R

Function in any programming language is an important part which is responsible for the smooth execution of the code. This article will help you to get familiar with functions in R programming. Also we will get in touch with the concept of packages in R.


This article is mostly focused on the theoretical part. We already have implemented functions in many of our previous articles. Still I will recommend my readers to try out each function to get used to this concept.

In my previous post, I had written about the multiple ways of creating the vector. Click on the link given below to read about it.

Creating vectors in R

What is a function?

Basic definition of a function is it is a set of code which is executed in order to get the specific result. Once the function has been defined, it can be called as many times as required.

In other words, we can define a function as blender which takes fruits as an input, it does some processing on them and gives juice as an output.

Below image shows working of functions

functions in R
What is function in R

There are basically two types of functions:

  1. Built in functions
  2. User defined functions

Built in functions

Built in functions are the library functions. They are pre compiled and we can use them directly in our script. In our previous articles we already have seen many of the built in functions in R.

Most of the functions are Parameterised functions. Parameterised functions expects input parameters. Some of them are executed even if we don’t pass parameters to them. In such case, default parameters are passed to them by the compiler itself. We can see the definition and information of any function by using the ‘?’ symbol in front them.

The built in functions we have seen so far are listed below. Keep trying them often to get good hands on practice with them.

  1. rnorm()
  2. c()
  3. seq()
  4. rep()
  5. print()
  6. sqrt()

To get more information about each of these functions, just type “?” before the function as shown below:

  • ? rnorm()
  • ? c()
  • ? seq()

User defined functions:

As the name suggests, the functions defined by the user to execute the specific set of code are known as user defined functions.

In R programming we can create our own function in simple way.

Let’s create an empty function first-

           f <- function(){
                # this is an empty function
           }
           f() 

Executing the above code we will get Null as an output. Because we have not written anything inside the function. Now to complete the function definition, let’s see the next code snippet.

          f <- function(){
            print("Hello") 
          }
          f() 

This is the simple function in R and It will print the world Hello.

What if we want to print some text multiple times? We are not going to copy and paste it for sure. If we do so, we are not going to call it as a programming. Here comes the part of passing parameters to the function and writing the parameterised functions.

Let’s create this as an assignment in R programming.

Write a function which will print the message for multiple times.

Let’s get started with it,

          f1 <- function(num){
               for(i in seq_len(num)){
                    print("You are doing good")
                }
           }
           f1(3)

Output:


> f1 <- function(num){          
+    for(i in seq_len(num)){
+       print("You are doing good")
+    }
+ }
>           
>           f1(3)
[1] "You are doing good"
[1] "You are doing good"
[1] "You are doing good" 

>

So we have written the function we wanted. But, what happens if I don’t specify the number at the time of calling the function?

Compiler is going to give me an error straight away!!

Have a look at below output:

 
>           f1 <- function(num){           
+             for(i in seq_len(num)){
+               print("You are doing good")
+             }
+           }
>           
>           f1()
Error in f1() : argument "num" is missing, with no default 

>

argument “num” is missing, with no default.

In other programming languages, we would also get the then what’s different in this?

With no default indicates that you can provide the default value for avoiding the error. This is called as the default argument.

How to pass the default value to the function?

To avoid above errors, we need to pass default argument in the function definition.

To differentiate between the outputs I have inserted the If-else condition in the function.

Have a look at below code for better understanding:

          f1 <- function(num = 1){ # passing default argument
              if(num <=1){
                 print("Executing the code with default value")
                 print("You are doing good")
                }
              else{
                for(i in seq_len(num)){
                  print("You are doing good")
                }
              }
            }
           f1(3) 

Output: Here you can see the different output

>           f1 <- function(num = 1){ # passing default argument
+              if(num <=1){
+                 print("Executing the code with default value")
+                 print("You are doing good")
+                }
+              else{
+                for(i in seq_len(num)){
+                  print("You are doing good")
+                }
+              }
+            }
>            
>            f1()
[1] "Executing the code with default value"
[1] "You are doing good"
 
 
>          f1 <- function(num = 1){ # passing default argument
+              if(num <=1){
+                 print("Executing the code with default value")
+                 print("You are doing good")
+                }
+              else{
+                for(i in seq_len(num)){
+                  print("You are doing good")
+                }
+              }
+            }
>            
>            f1(3)
[1] "You are doing good"
[1] "You are doing good"
[1] "You are doing good" 

>

Hence, we have seen the function with default argument as well.

In next article we will see what is package and which packages we have in R programming.

Keep me posted if you have any query. Your advice is priceless. Please provide any feedback regarding the quality of explanation or the complexity of content using below feedback form.

Feel free to comment or reach us directly via mail. Also you can contact us by Facebook, linkedin, twitter, instagram any of the platform you feel comfortable with.


Sumit Rajguru

Back to top