R Programming: Example of how to write a function in R

0

What is a function? A function allows you to create a program that has a set of instructions that you use repeatedly or contains a complex set of commands that is easier to encapsulate in a function. This function is written in order to carry out a specific task.

The R programming language has many prebuilt functions, but the goal of this post is to give you a few examples of how to write a function in R.

A function in R is basically built around the following structure:

function ( arglist ) {body}

The body is where you are going to write your function.

Our function is going to look like this generic example:

nameOfFunction <- function(argument1, argument2) {
 statements
 return(something)
}

Let's write a basic function that adds two numbers together:

addIt <- function(x,y) {
 added <- x + y
 return(added)
}

Now, go to R command line and write the following:

addIt(2,3)

How about another example where we square a number:

squareIt <- function(x) { 
 squared <- x * x
 return(squared)
}

Now, go to R command line and write the following:

squareIt(5)

And that is it. You now know how to write functions in R!

LEAVE A REPLY