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
map_dblandmap_intfail loudly if the result is the wrong type.~ .xis the shorthand lambda, with.xas the element.keepandreducecover filtering and folding.
Keywords and builtins used here
ckeeplengthlibrarylistmapmap2_dblmap_chrmap_dblmap_intpasteprintreducesum
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.
Step 1 of 4 in purrr, step 1 of 10 in Functional & text tools.