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$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))
rescale <- function(x) {
    
    # body
    x <- (x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
    
    # return value 
    return(x)
}
df$a <- rescale(df$a)
df$b <- rescale(df$b)
df$c <- rescale(df$c)
df$d <- rescale(df$d)

Functions are 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, buy it can be accepeted")
        print(x)
    } else {
        stop("Value is negative, the fuction must stop")
        print(x)
    }
    
}

3 %>% detect_sign()
## Value is positive
## [1] 3
0 %>% detect_sign()
## Warning in detect_sign(.): Value is not positive, buy it can be accepeted
## [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.rn = TRUE)
## [1] NA
x %>% mean(na.rn = TRUE, trim = 0.1)
## [1] NA
mean_remove_na <- function(x, na.rm = TRUE, ...) {
    
    avg <- mean(c, na.rm = na.rm, ...)
    
    return(avg)
}

x %>% mean_remove_na()
## Warning in mean.default(c, na.rm = na.rm, ...): argument is not numeric or
## logical: returning NA
## [1] NA
x %>% mean_remove_na(na.rm = FALSE)
## Warning in mean.default(c, na.rm = na.rm, ...): argument is not numeric or
## logical: returning NA
## [1] NA
x %>% mean_remove_na(trim = 0.1)
## Warning in mean.default(c, na.rm = na.rm, ...): argument is not numeric or
## logical: returning NA
## [1] NA

two type of functions

  • one that take a vector as the input
  • another that takes a data frame as the input

Return values