knitr::opts_chunk$set(echo = TRUE,
message = FALSE,
warning = FALSE)
# Load package
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.2.0 ✔ readr 2.1.6
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ ggplot2 4.0.2 ✔ tibble 3.3.1
## ✔ lubridate 1.9.5 ✔ tidyr 1.3.2
## ✔ purrr 1.2.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(nycflights13)
library(forcats)
library(lubridate)
library(nycflights13)
sample(10) + 10
## [1] 16 12 17 14 13 20 19 18 15 11
1:10 + 1:2
## [1] 2 4 4 6 6 8 8 10 10 12
1:10 + 1:3
## [1] 2 4 6 5 7 9 8 10 12 11
#data_frame(a = 1:10, b= 1:2)
#data_frame(a = 1:10, b= 1:3)
x <- sample(10)
x
## [1] 9 2 4 5 3 8 10 1 6 7
x[5]
## [1] 3
x[c(5,7)]
## [1] 3 10
x[x>5]
## [1] 9 8 10 6 7
a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -5))
str(a[1:2])
## List of 2
## $ a: int [1:3] 1 2 3
## $ b: chr "a string"
str(a[4])
## List of 1
## $ d:List of 2
## ..$ : num -1
## ..$ : num -5
a
## $a
## [1] 1 2 3
##
## $b
## [1] "a string"
##
## $c
## [1] 3.141593
##
## $d
## $d[[1]]
## [1] -1
##
## $d[[2]]
## [1] -5
a[1:2]
## $a
## [1] 1 2 3
##
## $b
## [1] "a string"
a[4]
## $d
## $d[[1]]
## [1] -1
##
## $d[[2]]
## [1] -5
a[[4]]
## [[1]]
## [1] -1
##
## [[2]]
## [1] -5
a[[4]][2]
## [[1]]
## [1] -5
a[[4]][[2]]
## [1] -5
A way to reduce duplication.
* Imperative Programming
* Functional Programming
Imperative Programing - explicit
# Example from the cheat sheet
for(i in 1:4){
j <- i + 10
print(j)
}
## [1] 11
## [1] 12
## [1] 13
## [1] 14
# Example 1: Numeric calculation + add 10
x <- 11:15
for(i in seq_along(x)){
j <- x[i] + 10
print(j)
}
## [1] 21
## [1] 22
## [1] 23
## [1] 24
## [1] 25
# save output
y <- vector("integer", length(x))
for(i in seq_along(x)){
y[i] <- x[i] + 10
print(y[i])
}
## [1] 21
## [1] 22
## [1] 23
## [1] 24
## [1] 25
# Outputs
y
## [1] 21 22 23 24 25
# Example 2: String Operations
x <-c("abc", "xyz")
y <- vector("character", length(x))
for(i in seq_along(x)){
y[i] <- x[i] %>% str_extract("a:z")
print(y[i])
}
## [1] NA
## [1] NA
#Output
y
## [1] NA NA
x <- 11:15
y <- vector("integer", length(x))
for(i in seq_along(x)){
y[i] <- x[i] + 10
print(y[i])
}
## [1] 21
## [1] 22
## [1] 23
## [1] 24
## [1] 25
# Outputs
y
## [1] 21 22 23 24 25
# Using map function
x
## [1] 11 12 13 14 15
map(.x = x,.f = ~.x + 10)
## [[1]]
## [1] 21
##
## [[2]]
## [1] 22
##
## [[3]]
## [1] 23
##
## [[4]]
## [1] 24
##
## [[5]]
## [1] 25
map_dbl(.x = x, .f = ~.x + 10)
## [1] 21 22 23 24 25
add_10 <- function(x) {x + 10}
11 %>% add_10()
## [1] 21
map_dbl(.x =x, .f = add_10)
## [1] 21 22 23 24 25