Functions in R (a bit deeper)

Copy and paste the following code to your R Studio platform or R version:

# Functions
hypotenuse <- function(side1, side2){
return(sqrt(side1^2 + side2^2))
}

hypotenuse(10, 10)
hypotenuse(side1 = 10, side2 = 25)
# if we do not assign a value to a parameter, we get an error
hypotenuse(25)
# we can deal with that, by assigning default values
hypotenuse <- function(side1 = 10, side2 = 10){
return(sqrt(side1^2 + side2^2))
}

hypotenuse()
hypotenuse(side1 = 5)

# Best practice though is demonstrated like this
hypotenuse <- function(side1 = NULL, side2 = NULL){
if(any(is.null(side1), is.null(side2))){
stop(“One of the sides is missing”)
}
return(sqrt(side1^2 + side2^2))
}

hypotenuse(12, 12)
hypotenuse(12)

# Or
hypotenuse <- function(side1, side2){
if(missing(side1) |missing(side2)){
stop(“One of the sides is missing”)
}
return(sqrt(side1^2 + side2^2))
}

hypotenuse(12, 12)
hypotenuse(12)

# Alternatively
hypotenuse <- function(side1 = NULL, side2 = NULL){
stopifnot(!missing(side1), !missing(side2))
return(sqrt(side1^2 + side2^2))
}

hypotenuse(12, 12)
hypotenuse(12)

# Optional Arguments
hypotenuse <- function(side1, side2, round = FALSE, …){
if(missing(side1) |missing(side2)){
stop(“One of the sides is missing”)
}
if(round){
return(round(sqrt(side1^2 + side2^2), …))
} else {
return(sqrt(side1^2 + side2^2))
}
}

hypotenuse(side1 = 12, side2 = 12)
hypotenuse(side1 = 12, side2 = 12, round = TRUE)
hypotenuse(12, 12, TRUE)

# The triple dots (…) in the function allow for functionalities like the following:
hypotenuse(side1 = 12, side2 = 12, round = TRUE, digits = 2)

# In R, simple mathematical notations are also functions and can be used like below:
‘+'(2,3)
‘*'(2,5)
# Of course, it is quite rare to use it like this, but this merely demonstrates that
# we can use the definition of a function as a symbol for further use, like below:
‘%***%’ <- function(x,y){
return(sqrt(x^2 + y^2))
}
10%***%2
hypotenuse(10,2)
# I believe that this is almost mind-blowing!!!!

# ———- A Mini Challenge ———— #
# Return the minimum of two numbers with your own function

minimum <- function(a = NULL, b = NULL){
if(any(is.null(a), is.null(b))){
stop(“One of the numbers is missing”)
}
if(a < b){
return(a)
}else if(b < a){
return(b)
}else{
return(“The values are equal”)
}
}

minimum()
minimum(2,2)
minimum(3,10)
minimum(25,20)

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s