pmap()
provides the entire tuple (row in the data frame case) to the function you're mapping.
So, if the function only uses a subset of the inputs it will see, you have to address that. I assume you're seeing a lot of:
Error in mutate_impl(.data, dots) :
Evaluation error: unused arguments (groupA = .l[[c(1, i)]], groupB = .l[[c(2, i)]])
There are a couple of options. First, you can include ...
as an argument to mop up any arguments fun
doesn't use. Second, you can use the ..i
pronouns to map your input to the function args by position. This generally terrifies me and I would not recommend it. However it does work.
library(tidyverse)
df <- tribble(
~groupA, ~groupB, ~v1, ~v2,
"A","C",4, 1,
"A","D",2, 3,
"A","D",1, 5
)
fun <- function(v1, v2) {
val <- sum(rnorm(10,v2,v2))
return(val)
}
fun(2,3)
#> [1] 28.57652
set.seed(1234)
df %>%
rowwise() %>%
mutate( t = fun(v1, v2))
#> Source: local data frame [3 x 5]
#> Groups: <by row>
#>
#> # A tibble: 3 x 5
#> groupA groupB v1 v2 t
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 A C 4 1 6.17
#> 2 A D 2 3 26.5
#> 3 A D 1 5 30.6
## absorb ununsed arguments with `...`
fun2 <- function(v1, v2, ...) {
val <- sum(rnorm(10,v2,v2))
return(val)
}
set.seed(1234)
df %>%
mutate( t = pmap_dbl(., fun2))
#> # A tibble: 3 x 5
#> groupA groupB v1 v2 t
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 A C 4 1 6.17
#> 2 A D 2 3 26.5
#> 3 A D 1 5 30.6
set.seed(1234)
df %>%
mutate( t = pmap_dbl(., ~ fun(v1 = ..3, v2 = ..4)))
#> # A tibble: 3 x 5
#> groupA groupB v1 v2 t
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 A C 4 1 6.17
#> 2 A D 2 3 26.5
#> 3 A D 1 5 30.6
Created on 2018-05-07 by the reprex package (v0.2.0).