R: Create Functions


I. Introduction

In R, and other programming languages, functions are a great way to simplify procedures that need to be done repeatedly.

# VERY GENERAL FUNCTION
function.name = function(arguments){
         #Code here that uses that typically uses arguments#
}

Example 1:

Lets create a function that simply adds 2 to any number input.

> # CREATE CUSTOM FUNCTION CALLED add.two
> add.two = function(x){
+   return(x + 2)
+ }
> 
> # RUN THE add.two FUNCTION
> add.two(5)
[1] 7

Example 2:

Lets create a function that converts feet and inches into cm.

> days.to.sec = function(no.days){
+   return(no.days*24*60*60)
+ }
> 
> # HOW MANY SECONDS IN A WEEK?
> days.to.sec(7)
[1] 604800

Example 3:

Lets create a function that uses two arguments.

> # CREATE FUNCTION THAT MULTIPLIES TWO NUMBERS
> multiply = function(x, y){
+   z = x*y
+   return(z)
+ }
> 
> # LETS FUN THE FUNCTION WE JUST CREATED :)
> multiply(x = 3, y = 5)
[1] 15

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.