1 Goal


The goal of this tutorial is to learn how to define default values for parameters in a handmade function.


2 Data import


# In this example we will use the open repository of plants classification Iris. 
data("iris")
summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

3 Defining a function


# The way to define a function is always 
# myfunction <- function(parameters){}

# Let's create a function to sum all the members of a vector and divide the sum by 5
sumanddivide <- function(my_vector, my_number){
  
  result <- sum(my_vector)/my_number
  return(result)
}

sumanddivide(iris$Sepal.Length, 5)
## [1] 175.3

4 Defining default values for the parameters of the function


# However we could define a default value for the denominator
sumanddivide <- function(my_vector, my_number = 5){
  
  result <- sum(my_vector)/my_number
  return(result)
}

# And now this should be the default value that we get when we don't specify the second parameter
sumanddivide(iris$Sepal.Length, 5)
## [1] 175.3
# When we don't specify the denominator we get vector/5
sumanddivide(iris$Sepal.Length)
## [1] 175.3
# However we can change the value and get any result we want
sumanddivide(iris$Sepal.Length, 10)
## [1] 87.65

5 Conclusion


In this tutorial we have learnt how to define default values for the parameters of a function. This could be very useful if we don’t want the user to introduce all the parameters every time he uses the function. It also prevents the function to crash when some parameter is not introduced.