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 - 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)
}
## [1] 21 0 0 0 0
## [1] 21 22 0 0 0
## [1] 21 22 23 0 0
## [1] 21 22 23 24 0
## [1] 21 22 23 24 25
# output
y
## [1] 21 22 23 24 25
# example 2: string operation - extract fist letter
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] "a"
## [1] "x"
# output
y
## [1] "a" "x"
The 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)
}
## [1] 21 0 0 0 0
## [1] 21 22 0 0 0
## [1] 21 22 23 0 0
## [1] 21 22 23 24 0
## [1] 21 22 23 24 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}
22 %>% add_10()
## [1] 32
map_dbl(.x = x, .f = add_10)
## [1] 21 22 23 24 25
# create the data frame
df <- tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
map_dbl(df, mean)
## a b c d
## 0.06479129 0.21072924 -0.07314460 -0.18601571
map_dbl(df, median)
## a b c d
## 0.10989203 0.30671889 -0.07584076 -0.04193528
map_dbl(df, sd)
## a b c d
## 0.7287577 0.8803627 1.1368318 1.2436272