Chapter 20

Introduction

Vector Basics

Important Types of Atomic Vector

Using Atomic Vectors

sample(10) + 10
##  [1] 17 19 11 16 15 13 12 14 20 18
1:10 + 1:2
##  [1]  2  4  4  6  6  8  8 10 10 12
1:10 + 1:3
## Warning in 1:10 + 1:3: longer object length is not a multiple of shorter object
## length
##  [1]  2  4  6  5  7  9  8 10 12 11
data.frame(a =1:10, b = 1:2)
##     a b
## 1   1 1
## 2   2 2
## 3   3 1
## 4   4 2
## 5   5 1
## 6   6 2
## 7   7 1
## 8   8 2
## 9   9 1
## 10 10 2
data.frame(a =1:9, b = 1:3)
##   a b
## 1 1 1
## 2 2 2
## 3 3 3
## 4 4 1
## 5 5 2
## 6 6 3
## 7 7 1
## 8 8 2
## 9 9 3
x <- sample(10)
x
##  [1]  1  5  6  8  2  7  3  9  4 10
x[c(5, 7)]
## [1] 2 3
x[x>5]
## [1]  6  8  7  9 10

Recursive Vectors (Lists)

# The three principles of lists

## Lists have rounded corners. Atomic vectors have square corners. 
x1 <- list(c(1, 2), c(3, 4))

## Children are drawn inside their parent and have a slightly darker background.
x2 <- list(list(1, 2), list(3, 4))

## The orientation of the children (i.e. rows or columns) isn't important. 
x3 <- list(1, list(2, list(3)))

# I attempted to include the image from the textbook, but it was beyond my current ability. :)
a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -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]]
## [[1]]
## [1] -1
## 
## [[2]]
## [1] -5
a[[4]][2]
## [[1]]
## [1] -5
a[[4]][[2]]
## [1] -5

Chapter 21

Introduction

For Loops

# 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
j
## [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
# Output
y
## [1] 21 22 23 24 25
# Example 2: String Operation - Extract first letter
x <- c("abc", "xyz")

x
## [1] "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] "a"
## [1] "x"
# Output
y
## [1] "a" "x"

For Map Functions

# Example 1: Numeric Calculation - Add 10
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
# Output
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