x <- list(1, 1, 1)
y <- list(10, 20, 30)
z <- list(100, 200, 300)
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)
# 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)
Run the code above in your browser using DataLab