Simple Function without Arguments

greetings <- function(){
  
  print("Hi, there!")

}

greetings()
## [1] "Hi, there!"

Simple Function with an Argument

findRange <- function(vector){

max(vector, na.rm = TRUE) - min(vector, na.rm = TRUE)
  
}

vec1 <- c(seq(1,10, 1), rep(NA, 5))
 

findRange(vec1)
## [1] 9

Function that returns an Object

squared <- function(x){
  
    x_squared <- x^2
    
    return(x_squared)
}

squared(9)
## [1] 81

Function with default Arguments

addThreeNumbers <- function(a = 1, b = 3, c){
  
  x <- c(a, b, c)
  
  sum(x)
  
}

addThreeNumbers(c = 3)
## [1] 7
addThreeNumbers(a = 5, b = 6, c = 3)
## [1] 14

Functions with Warnings

printPositiveValue <- function(x){
    if (x >= 0) print(x) else
    warning("x needs greater than zero!")
}

printPositiveValue(10)
## [1] 10
printPositiveValue(-10)
## Warning in printPositiveValue(-10): x needs greater than zero!