# Load packages

# Core
library(tidyverse)
library(tidyquant)
library(dplyr)

CH 19 Functions

Introduction

When should you write a function?

# For reporducible work 
set.seed(2234)
# 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$b, 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 1      0.161 0.741 0.222
##  2 0.953  0.188 0     0.474
##  3 0.199  0.380 0.285 0.499
##  4 0.764  0.737 0.988 0.522
##  5 0.759  0.364 0.537 0.243
##  6 0.780  1     0.922 0    
##  7 0.408  0.425 0.500 0.618
##  8 0      0     0.724 0.227
##  9 0.661  0.537 0.800 0.378
## 10 0.0876 0.411 1     1
rescale <- function(x) {
    
    # body 
    x <- (df$a - 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 1      1      1      1     
##  2 0.953  0.953  0.953  0.953 
##  3 0.199  0.199  0.199  0.199 
##  4 0.764  0.764  0.764  0.764 
##  5 0.759  0.759  0.759  0.759 
##  6 0.780  0.780  0.780  0.780 
##  7 0.408  0.408  0.408  0.408 
##  8 0      0      0      0     
##  9 0.661  0.661  0.661  0.661 
## 10 0.0876 0.0876 0.0876 0.0876

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()
## [1] 3
0 %>% detect_sign()
## [1] 0
# -1 %>% detect_sign()

Function arguments

?mean
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