STAT1003 – Statistical Techniques
Dr. Emi Tanaka
Australian National University
These slides are best viewed on a modern browser like Google Chrome on a desktop or laptop. Some interactive components may require some time to fully load.
nacross function in dplyr can do this without for loopsdata.frameFunctions can be broken into three components:
formals(), the list of arguments,body(), the code inside the function, andenvironment()1.Functions in R are created using function() with binding to a name using <- or =
{}.purrr
purrr is part of the core tidyverse packages.map and walk functions.purrr have been design so that that input are consistent.map functions in purrrmap(.x, .f, ...) returns a listmap_chr(.x, .f, ...) returns a vector of charactermap_dbl(.x, .f, ...) returns a vector of numericmap_int(.x, .f, ...) returns a vector of integermap_lgl(.x, .f, ...) returns a vector of logicalpurrrmap_if(.x, .p, .f, ...) uses .p to determine if .f will be applied to .xmap_at(.x, .at, .f, ...) applies .f to .x at .at (name or position)map_depth(.x, .depth, .f, ...) apples .f to .x at a specific depth level of a nested vectorlapply, Map, mapply, sapply, tapply, apply, and vapply are variants of functional programming in Base Rpurrr::map is a variant of lapply (which always returns list)purrr::pmap is a variant of Map (which takes more than one input)sapply doesn’t require users to specify the output type, instead it’ll try to figure out what looks best for the user… great for interactive use but require great caution for programming\(x) to define anonymous functions.x as a special placeholder for inputpurrr functions:tidyverse functions would support this formula approach to anonymous function, but likely not outside of that ecosystem unless developers adopt the same system.map2 variants in purrr.x (as before) and the second is .ypmap variants in purrrpurrrUsing names of input
imap(x) variants are shorthand for map2(x, names(x))Expecting no return object
walk variantsreduce function in purrrreduce(.x, .f) applies a function .f cumulatively to the elements of .x, from left to right.reduce(c(1, 2, 3, 4), sum) is equivalent to sum(sum(sum(1, 2), 3), 4)accumulate(.x, .f) is similar to reduce, but it returns the intermediate results as well.purrr cheatsheet


STAT1003 – Statistical Techniques