STAT 220
It would be nice to iterate this process so that the same function/operation can be ran multiple times
What is a For loop?
for
loop componentsthe for()
function is used to specify
for(i in items)
^ ^
| |
| |___ object we are drawing from
|
|
obj. we write each item to
for
loop componentsThe brackets {}
for( i in items ){
|~~~~~~~~~~~~~~~~|
|~~~~~~~~~~~~~~~~|
|~~~~~~~~~~~~~~~~| code we need perform on each iteration.
|~~~~~~~~~~~~~~~~|
|~~~~~~~~~~~~~~~~|
}
for
loops tinydata
if x is numeric then standardize, else just return x
standardize <- function(x, ...){ # ... placeholder for optional args
if (is.numeric(x)){ # condition
(x - mean(x, ...))/sd(x, ...) # if TRUE, standardize
} else{ # else (FALSE)
x # return x unchanged
}
}
standardize(c(2,4,6,8, 10))
[1] -1.2649111 -0.6324555 0.0000000 0.6324555 1.2649111
[1] "2" "4" "6" "8" "10"
[1] -1.1618950 -0.3872983 0.3872983 1.1618950 NA
# allocate storage in a new data frame
scaled_tinydata <- tinydata %>% mutate(x = NA, y = NA, z = NA)
for (i in seq_along(tinydata)){
scaled_tinydata[, i] <- standardize(tinydata[[i]])
}
scaled_tinydata
# A tibble: 3 × 4
case x y z
<chr> <dbl> <dbl> <dbl>
1 a -1 -0.398 0.873
2 b 0 -0.740 -1.09
3 c 1 1.14 0.218
ca15-yourusername
repository from Github10:00
Functional function will apply the same operation (function) to each element of a vector, matrix, data frame or list.
apply
family of commandspurrr
package: map
family of commandsapply
family of commandsR has a family of commands that apply a function to different parts of a vector, matrix or data frame
lapply(X, FUN): applies FUN to each element in the vector/list X
Example: lapply(tinydata, FUN = mean)
sapply(X, FUN): works like lapply, but returns a vector
Example: sapply(tinydata, FUN = mean)
purrr
packagepowerful package for iteration with the same functionality as apply commands, but more readable
map(.x, .f)
maps the function .f
to elements in the vector/list .x
lapply
with tinydata
tinydata
as a list whose elements are column vectors (variables)purrr::map
purrr::map_dbl
map_dbl
is equivalent to sapply
purrr::map_df
standardize
function gives us a list of standardized values
purrr::map_df
In purrr
, the map_df
is equal to lapply
+ bind_cols
:
map_dfr
: Getting Quantilesmap_dfc
: Getting Quantiles10:00