Chapter 20 Vectors

Introduction

Vector basics

Important types of atomic vectors

Using atomic vectors

sample(10) + 10
##  [1] 19 16 15 18 14 13 20 11 17 12
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:10, b=1:3)
x <- sample(10)
x
##  [1]  7  8  4  2  9  6  5 10  3  1
x[c(5,7)]
## [1] 9 5
x[c(-1, -4)]
## [1]  8  4  9  6  5 10  3  1
x <- c(43, 32, NA, 45, 12, NA)
# All non-missing values of x
x[!is.na(x)]
## [1] 43 32 45 12
# all even (or missing !) values of x
x[x %% 2 == 0]
## [1] 32 NA 12 NA
# Subset with a character vector
x <- c(purple = 1, water = 2, bottle = 3) 
x[c("purple", "water", "bottle")]
## purple  water bottle 
##      1      2      3

Recursive vectors

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]] [1]
## [[1]]
## [1] -1
a[[4]] [[1]]
## [1] -1

Attributes

Augmented vectors

Chapter 21 Iteration

Introduction

For loops

# example from the cheatsheet
for (i in 1:4) {
    j <- i +10
    print(j)
    
}
## [1] 11
## [1] 12
## [1] 13
## [1] 14
# example 1: numeric calculation - 10
z <- 11:15

for (i in seq_along(z)) {
    j <- z[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(z)) {
    y[i] <- z[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
d <- c("abc", "xyz")

k <- vector("character", length(d)) 
for (i in seq_along(d)) {
    k[i] <- d[i] %>% str_extract("[a-z]")
    print(k[i])
    
}
## [1] "a"
## [1] "x"
# output
k
## [1] "a" "x"

For loop variations

For loops vs functionals

The map functions

# example 1: numeric calculation - 10
z <- 11:15

# save output
y <- vector("integer", length(x)) 
for (i in seq_along(z)) {
    y[i] <- z[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
map(.x = z, .f = ~.x + 10)
## [[1]]
## [1] 21
## 
## [[2]]
## [1] 22
## 
## [[3]]
## [1] 23
## 
## [[4]]
## [1] 24
## 
## [[5]]
## [1] 25
map_dbl(.x = z, .f = ~.x +10)
## [1] 21 22 23 24 25
add_10 <- function(z) {z +10}
map_dbl(.x = z, .f = add_10)
## [1] 21 22 23 24 25