CH19 Functions

Introduction

When Should you write a function?

# Create a data frame
df <- tibble::tibble(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)
#Rescale Each Column

df$a <- (df$a - min(df$a, na.rm = TRUE)) / 
  (max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$b <- (df$b - min(df$b, na.rm = TRUE)) / 
  (max(df$b, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$c <- (df$c - min(df$c, na.rm = TRUE)) / 
  (max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$d, na.rm = TRUE)) / 
  (max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))

df
## # A tibble: 10 × 4
##         a     b     c      d
##     <dbl> <dbl> <dbl>  <dbl>
##  1 0.265  0.421 0.895 1     
##  2 0.614  0.639 0.961 0     
##  3 0.582  0.428 0.287 0.640 
##  4 0.0873 0.692 0     0.0444
##  5 0.0726 1.03  0.807 0.0678
##  6 0.529  1.30  0.194 0.290 
##  7 0      0.578 0.415 0.101 
##  8 0.495  0.467 0.372 0.240 
##  9 0.252  0     1     0.269 
## 10 1      0.111 0.564 0.525
rescale <- function(x) {
    
    # body
    x <- (x - min(x, na.rm = TRUE)) /
        (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
    
    # return values
    return(x)
}
df$a <- rescale(df$a)
df$b <- rescale(df$b)
df$c <- rescale(df$c)
df$d <- rescale(df$d)

df
## # A tibble: 10 × 4
##         a      b     c      d
##     <dbl>  <dbl> <dbl>  <dbl>
##  1 0.265  0.324  0.895 1     
##  2 0.614  0.492  0.961 0     
##  3 0.582  0.329  0.287 0.640 
##  4 0.0873 0.533  0     0.0444
##  5 0.0726 0.791  0.807 0.0678
##  6 0.529  1      0.194 0.290 
##  7 0      0.445  0.415 0.101 
##  8 0.495  0.359  0.372 0.240 
##  9 0.252  0      1     0.269 
## 10 1      0.0852 0.564 0.525

Functions are for Humans and Computers

Conditional Execution

detect_sign <- function(x) {
    
    if(x > 0) {
        message("Value is Positive")
        print(x)
    } else if(x == 0) {
        warning("Value is not positive, but it can be accepted")
        print(x)
        
       } else {
           stop("Value is negative, the function must stop")
           print(x)
    }
    
}

3 %>% detect_sign()
## Value is Positive
## [1] 3
0 %>% detect_sign()
## Warning in detect_sign(.): Value is not positive, but it can be accepted
## [1] 0
# -1 %>% detect_sign()

Function Arguments

?mean
## starting httpd help server ... done
x <- c(1:10, 100, NA)
x
##  [1]   1   2   3   4   5   6   7   8   9  10 100  NA
x %>% mean()
## [1] NA
x %>% mean(na.rm = TRUE)
## [1] 14.09091
x %>% mean(na.rm = TRUE, trim = 0.1)
## [1] 6
mean_remove_na <- function(x, na.rm = TRUE, ...) {
    
    avg <- mean(x, na.rm = na.rm, ...)
    
    return(avg)
}

x %>% mean_remove_na()
## [1] 14.09091
x %>% mean_remove_na(na.rm = FALSE)
## [1] NA
x %>% mean_remove_na(trim = 0.1)
## [1] 6

Two Types of Functions

Return Values