# Load package
library(tidyverse)
library(tidyquant)

Introduction

When should you write a function

df <- tibble::tibble(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)
# Rescale ach colum

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 0.659  0.211   0.702  0.948
##  2 0.848  0.794   0.164  0.636
##  3 0.618  0.544   0.627  0.222
##  4 0      0.00329 0.721  0    
##  5 0.288  0.993   0.0546 0.426
##  6 0.364  1       0      0.596
##  7 1      0.714   0.398  0.219
##  8 0.105  0.390   1      0.191
##  9 0.0698 0       0.366  1    
## 10 0.377  0.793   0.781  0.874
rescale <- function(x) {
    
    #body
    x <- (x- min(x, na.rm = TRUE)) / 
  (max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
}
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.659  0.211   0.702  0.948
##  2 0.848  0.794   0.164  0.636
##  3 0.618  0.544   0.627  0.222
##  4 0      0.00329 0.721  0    
##  5 0.288  0.993   0.0546 0.426
##  6 0.364  1       0      0.596
##  7 1      0.714   0.398  0.219
##  8 0.105  0.390   1      0.191
##  9 0.0698 0       0.366  1    
## 10 0.377  0.793   0.781  0.874

Functions are for humans and computers

Condisional execution

detect_sign <- function(x) {
    
    if(x > 0) {
        message("Value is posetive")
        print(x)  
    } else if(x == 0) {
        warning("Value is not posetive, but 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

Funcion Argument

?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 he input another that takes the data frames as input

Return Values