typestar

purrr basics in R

map returns a list; the typed variants return a vector of that type.

library(purrr)

nums <- list(1:3, 4:6, 7:9)

sums <- map_dbl(nums, sum)
firsts <- map_int(nums, ~ .x[[1]])
labels <- map_chr(nums, ~ paste(.x, collapse = "-"))
nested <- map(nums, ~ .x * 2)

pairs <- map2_dbl(1:3, 4:6, ~ .x * .y)
filtered <- keep(nums, ~ sum(.x) > 10)
total <- reduce(nums, ~ c(.x, .y))

print(sums)
print(firsts)
print(labels)
print(length(filtered))
print(pairs)
print(total)

How it works

  1. map_dbl and map_int fail loudly if the result is the wrong type.
  2. ~ .x is the shorthand lambda, with .x as the element.
  3. keep and reduce cover filtering and folding.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
394
Tokens
140
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 1 of 4 in purrr, step 1 of 10 in Functional & text tools.

Next →