typestar

purrr over several inputs in R

map2 walks two vectors together; pmap walks a list of them.

library(purrr)

langs <- c("r", "python")
tpms <- c(96, 104)

print(map2_chr(langs, tpms, ~ paste0(.x, "=", .y)))

args <- list(lang = langs, tpm = tpms, stars = c(3L, 3L))
print(pmap_chr(args, function(lang, tpm, stars)
  sprintf("%s %d (%d stars)", lang, tpm, stars)))

walk2(langs, tpms, ~ cat(.x, .y, "\n"))
print(imap_chr(set_names(tpms, langs), ~ paste(.y, .x)))

How it works

  1. map2 requires both inputs to be the same length.
  2. pmap takes a list or a data frame of arguments.
  3. walk is map for side effects, returning the input.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
366
Tokens
127
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →