suppressPackageStartupMessages(library(tidyverse))

1 Today’s Agenda

Today’s lessons are:

  1. Review of purrr and piping.
  2. Parallel mapping
  3. List columns
  4. An analysis using both

2 Resources

All are from Jenny’s purrr tutorial. Specifically:

The all-encompassing application near the bottom of the worksheet is from Jenny’s “Sample from groups, n varies by group”

3 Review

3.1 purrr

map(x, f, ...) returns a list with elements:

  • f(x[[1]], ...)
  • f(x[[2]], ...)

map_dbl, map_lgl, etc to return a vector.

We can specify a pre-defined f, or write it on-the-fly, or another way that we didn’t touch on last time. Example with “squaring” function:

  • map(x, square) where square <- function(t) t^2;
  • map(x, function(t) t^2); or
  • map(x, ~ (.x)^2) (function variable is .x by convention).

3.2 piping: .

We know that a %>% b() is the same as b(a).

Want to refer to a in addition to the first argument? Specify it as a .. Example:

Gotcha:

Case 1: LHS (= left-hand side) not put as first argument when . appears in RHS:

log(8, base=2)
[1] 3
## is identical to...
2 %>% log(8, base=.)
[1] 3

Case 2: LHS is still put as first argument, even when . appears in RHS:

c(ncol(mtcars), nrow(mtcars))
[1] 11 32
## is NOT identical to...
1:10 %>% c(min(.), max(.))
 [1]  1  2  3  4  5  6  7  8  9 10  1 10

Trick: Use {} to “absorb” the placement of LHS as first argument:

1:10 %>% {c(min(.), max(.))}
[1]  1 10

3.3 Worksheet

To get participation points for today, we’ll be filling out the cm104-exercise.Rmd file.

Add this to your participation repo.

LS0tCnRpdGxlOiAiU1RBVCA1NDdNIENsYXNzIE1lZXRpbmcgMDQ6IGBwdXJycmAgYW5kIExpc3QgQ29sdW1ucyIKb3V0cHV0OgogICAgaHRtbF9ub3RlYm9vazoKICAgICAgICB0b2M6IHRydWUKICAgICAgICB0aGVtZTogY2VydWxlYW4KICAgICAgICBudW1iZXJfc2VjdGlvbnM6IHRydWUKZWRpdG9yX29wdGlvbnM6IAogIGNodW5rX291dHB1dF90eXBlOiBpbmxpbmUKLS0tCgpgYGB7cn0Kc3VwcHJlc3NQYWNrYWdlU3RhcnR1cE1lc3NhZ2VzKGxpY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