# Load packages

# Core
library(tidyverse)
library(tidyquant)

Functions

When should you write a function?

# For reproducible work 
set.seed(1234) 

# Create a data from 
df <- tibble::tibble(
    a = rnorm(10),
    b = rnorm(10),
    c = rnorm(10),
    d = rnorm(10)
)
# Re-scale each Function 

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$a, na.rm = TRUE)) / 
  (max(df$b, na.rm = TRUE) - min(df$b, na.rm = TRUE))
df$c <- (df$c - min(df$a, na.rm = TRUE)) / 
  (max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$a, 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.332 -0.140   0.0663   0.336 
##  2 0.765 -0.292  -0.243   -0.145 
##  3 1     -0.227  -0.218   -0.216 
##  4 0      0.0189  0.227   -0.153 
##  5 0.809  0.281  -0.343   -0.496 
##  6 0.831 -0.0323 -0.716   -0.356 
##  7 0.516 -0.150   0.284   -0.664 
##  8 0.524 -0.267  -0.506   -0.409 
##  9 0.519 -0.245  -0.00748 -0.0897
## 10 0.424  0.708  -0.463   -0.142
rescale <- function(x) {
    #body 
   x <- (x - min(df$a, na.rm = TRUE)) / 
  (max(x, na.rm = TRUE) - min(x, na.rm = TRUE)) 
   
   #return x 
   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.332 -0.140   0.0663   0.336 
##  2 0.765 -0.292  -0.243   -0.145 
##  3 1     -0.227  -0.218   -0.216 
##  4 0      0.0189  0.227   -0.153 
##  5 0.809  0.281  -0.343   -0.496 
##  6 0.831 -0.0323 -0.716   -0.356 
##  7 0.516 -0.150   0.284   -0.664 
##  8 0.524 -0.267  -0.506   -0.409 
##  9 0.519 -0.245  -0.00748 -0.0897
## 10 0.424  0.708  -0.463   -0.142

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 ")
    } else {
        stop("Value is negative, the function must stop")
    }
}

3 %>% detect_sign() 
## [1] 3
0 %>% detect_sign() 
# -1 %>% detect_sign() 

Functions 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: + one that takes a vector as the input + another that takes a data frame as the input