06 – Functions

Sebastian Raschka 6/17/2020

Source file: https://github.com/rasbt/R-notes/blob/master/06-functions.Rmd

Functions

Basic Function Syntax

mean_squared_error <- function(x, y){
  mean_diff <- mean(x - y)
  mean_diff^2
}

mean_squared_error(c(1, 2, 3), c(1, 2, 5))

## [1] 0.4444444

and

mean_squared_error <- function(x, y){
  mean_diff <- mean(x - y)
  return(mean_diff^2)
}

mean_squared_error(c(1, 2, 3), c(1, 2, 5))

## [1] 0.4444444

both return 0.4444444

Saving and Loading Functions

R notes screenshot

Function Parameters and Arguments

mean_squared_error <- function(x, y){
  mean_diff <- mean(x - y)
  mean_diff^2
}

mean_squared_error(c(1, 2, 3), c(1, 2, 5))

## [1] 0.4444444
some_func <- function(a = 'H', b = 'ello')
  cat(a, b, '\n')

some_func()

## H ello

some_func(a = 'C')

## C ello

some_func(b = 'i')

## H i
some_func(a = 'C', b = 'old')

## C old

some_func(b = 'old', a = 'C')

## C old

some_func('C', 'old')

## C old
standardize <- function(x, na.rm = TRUE) {
  (x - mean(x, na.rm = na.rm)) / sd(x, na.rm = na.rm)
}

vec <- c(1.1, 5.2, 2.1, 1.2, NA)
standardize(vec)

## [1] -0.6770588  1.4582806 -0.1562443 -0.6249774         NA

standardize(vec, na.rm = FALSE)

## [1] NA NA NA NA NA
formals(standardize)

## $x
## 
## 
## $na.rm
## [1] TRUE
args(standardize)

## function (x, na.rm = TRUE) 
## NULL

“…” Arguments

standardize <- function(x, na.rm = TRUE) {
  (x - mean(x, na.rm = na.rm)) / sd(x, na.rm = na.rm)
}

vec <- c(1.1, 5.2, 2.1, 1.2, NA)
standardize(vec)

## [1] -0.6770588  1.4582806 -0.1562443 -0.6249774         NA
standardize2 <- function(x, ...) {
  (x - mean(x, ...)) / sd(x, na.rm = ...)
}

vec <- c(1.1, 5.2, 2.1, 1.2, NA)
standardize2(vec) # note that na.rm = FALSE by default in mean() and sd()

## [1] NA NA NA NA NA

standardize2(vec, na.rm = TRUE)

## [1] -0.6770588  1.4582806 -0.1562443 -0.6249774         NA

Function Documentation

Importing Code

source()

Developing R Packages

Vectorization