x <- list(1, 1, 1)
y <- list(10, 20, 30)
z <- list(100, 200, 300)
map2(x, y, ~ .x + .y)
# Or just
map2(x, y, `+`)
pmap(list(x, y, z), sum)
# Matching arguments by position
pmap(list(x, y, z), function(first, second, third) (first + third) * second)
# Matching arguments by name
l <- list(a = x, b = y, c = z)
pmap(l, function(c, b, a) (a + c) * b)
# Split into pieces, fit model to each piece, then predict
by_cyl <- mtcars %>% split(.$cyl)
mods <- by_cyl %>% map(~ lm(mpg ~ wt, data = .))
map2(mods, by_cyl, predict)
# Vectorizing a function over multiple arguments
df <- data.frame(
x = c("apple", "banana", "cherry"),
pattern = c("p", "n", "h"),
replacement = c("P", "N", "H"),
stringsAsFactors = FALSE
)
pmap(df, gsub)
pmap_chr(df, gsub)
# Use `...` to absorb unused components of input list .l
df <- data.frame(
x = 1:3,
y = 10:12,
z = letters[1:3]
)
plus <- function(x, y) x + y
if (FALSE) {
# this won't work
pmap(df, plus)
}
# but this will
plus2 <- function(x, y, ...) x + y
pmap_dbl(df, plus2)
# The "p" for "parallel" in pmap() is the same as in base::pmin()
# and base::pmax()
df <- data.frame(
x = c(1, 2, 5),
y = c(5, 4, 8)
)
# all produce the same result
pmin(df$x, df$y)
map2_dbl(df$x, df$y, min)
pmap_dbl(df, min)
# If you want to bind the results of your function rowwise, use:
# map2_dfr() or pmap_dfr()
ex_fun <- function(arg1, arg2){
col <- arg1 + arg2
x <- as.data.frame(col)
}
arg1 <- 1:4
arg2 <- 10:13
map2_dfr(arg1, arg2, ex_fun)
# If instead you want to bind by columns, use map2_dfc() or pmap_dfc()
map2_dfc(arg1, arg2, ex_fun)
Run the code above in your browser using DataLab