R: Create Functions in R

Learning to use functions in R will improve your programming skills greatly. The way I think of functions is I think of them as mini programs you create inside your program.

Below I create function called Times2. The syntax for creating a function is:

FunctionName <- function(parameters) {
              Action (body of the function)    
              }

rFunc.jpg

You call the function simply by calling it’s name and giving it a parameter.

rFunc1.jpg

You can even pass the function a vector

rFunc2.jpg

Nest a Function

You can nest functions – call a function from inside another function

rFunc3

Assign Function Output to a Variable

Below, I took the print statements out of the functions and assigned Times2Sqr(2) to a variable y

rFunc4.jpg

You can work with this variable just like any other variable

rFunc5.jpg

Recursive Function

Recursive Functions are functions that call themselves.

I am using If and Else in this example. If they are foreign to you, don’t worry, I will cover them in a future lesson.

rFunc6.jpg

The Code

# create a function in R

Times2 <- function(x) {
   y <- x*2
   print(y)
   }
 
Times2(2)
Times2(8)

x <- c(1,3,6,3)
Times2(x)

#nested functions
Times2Sqr <- function (x) {
   y <- Times2(x)**2
   print(y)
   }
 
Times2Sqr(2)

# assign function value to variable
Times2 <- function(x) {
   y <- x*2
   }
Times2Sqr <- function (x) {
   y <- Times2(x)**2
   }
 
y <- Times2Sqr(2)

#recursive functions
Recur <- function(x) {
 if (x==0)
 return(1)
 else 
 return (x * Recur(x-1))
 
}

Recur(6)

Please Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s