# Load packages

# Core
library(tidyverse)
library(tidyquant)

Functions

When to write a function

NOTE: The website no longer reflects the website as shown in the video. The chapter for functions on r for data science is now 25 instead of 19 and the chapter is set up a bit differently from how it was in the video.

# create a data frame
df <- tibble(
  a = rnorm(5),
  b = rnorm(5),
  c = rnorm(5),
  d = rnorm(5),
)
df |> mutate(
  a = (a - min(a, na.rm = TRUE)) / 
    (max(a, na.rm = TRUE) - min(a, na.rm = TRUE)),
  b = (b - min(b, na.rm = TRUE)) / 
    (max(b, na.rm = TRUE) - min(b, na.rm = TRUE)),
  c = (c - min(c, na.rm = TRUE)) / 
    (max(c, na.rm = TRUE) - min(c, na.rm = TRUE)),
  d = (d - min(d, na.rm = TRUE)) / 
    (max(d, na.rm = TRUE) - min(d, na.rm = TRUE)),
)
## # A tibble: 5 × 4
##       a     b     c     d
##   <dbl> <dbl> <dbl> <dbl>
## 1 0.683 1     0     0.393
## 2 0.605 0.789 0.267 1    
## 3 0.911 0.696 1     0.159
## 4 0     0     0.394 0    
## 5 1     0.318 0.778 0.830
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 |> mutate(
  a = rescale(a),
  b = rescale(b),
  c = rescale(c),
  d = rescale(d),
)
## # A tibble: 5 × 4
##       a     b     c     d
##   <dbl> <dbl> <dbl> <dbl>
## 1 0.683 1     0     0.393
## 2 0.605 0.789 0.267 1    
## 3 0.911 0.696 1     0.159
## 4 0     0     0.394 0    
## 5 1     0.318 0.778 0.830

Functions are for humans and computers

Conditional execution

detect_sign <- function(x) {
    
    if(x > 0) {
        message("Value is postitive")
        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()
## Error in `detect_sign()`:
## ! Value is negative the function must stop

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 = .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 = .1)
## [1] 6

two types of functions one that takes a vector as input another that takes a data frame as the input

Return Values