Chapter 20 Vectors

Introduction

Vector Basics

x <- list("a", "b", 1:10)
length(x)
## [1] 3

Important types of automic vector

typeof(1)
## [1] "double"
typeof(1L)
## [1] "integer"
1.5L
## [1] 1.5

Using automic vectors

sample(10) + 10
##  [1] 15 11 19 12 17 18 13 20 14 16
1:10 + 1:2
##  [1]  2  4  4  6  6  8  8 10 10 12
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
x <- sample(10)
x
##  [1]  9 10  8  1  6  7  2  3  4  5
x[c(5, 7)]
## [1] 6 2
x[x>5]
## [1]  9 10  8  6  7

Recursive vectors

a <- list(a = 1:3, b = "a string", c = pi, d = list)
a
## $a
## [1] 1 2 3
## 
## $b
## [1] "a string"
## 
## $c
## [1] 3.141593
## 
## $d
## function (...)  .Primitive("list")
a[1:2]
## $a
## [1] 1 2 3
## 
## $b
## [1] "a string"
a[[4]]
## function (...)  .Primitive("list")
#a[[4]][2]

Attributes

Augmented vectors

x <- factor(c("ab", "cd", "ab"), levels = c("ab", "cd", "ef"))
typeof(x)
## [1] "integer"
attributes(x)
## $levels
## [1] "ab" "cd" "ef"
## 
## $class
## [1] "factor"

Chapter 21 Iteration

Introduction

For loops

for (i in 1:4){
    j <- i + 10
    print(j)
}
## [1] 11
## [1] 12
## [1] 13
## [1] 14
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
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
y
## [1] 21 22 23 24 25
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])
#}
#y

The map functions

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
y
## [1] 21 22 23 24 25
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