I want to loop over the rows of a tibble
, one column should hold the name the corresponding slot should have in the output and the other columns are the arguments to the function.
I know how to solve that, but I was wondering whether there is any possibility to do the naming inside the pmap
function?
library(purrr)
library(tibble)
params <- tibble(nm = LETTERS[1:2], x = 1:2, y = 2:3)
## this has one addional level of nesting
pmap(params, function(nm, x, y) {
set_names(list(x + y), nm)
}) # %>% flatten would remove the unnecessary level
## correct format but mixes tidyverse syntax with base syntax
map(split(params, params$nm), ~ .x$x + .x$y)
## correct format & tidyverse syntax but naming must happen **outside**
pmap(params, function(nm, x, y) {
x + y
}) %>%
set_names(params$nm)
Expected result like in version 2 or 3, in tidyverse
style, but without the necessity to rename the result afterwards.
The way pmap
works is that it takes the names from the names of the first argument so this does not do post processing of thepmap
output but it does add such names before running pmap
so that the input corresponds to what it expects.
params %>%
mutate(nm = set_names(nm)) %>%
pmap(function(nm, x, y) {
x + y
})
giving
$A
[1] 3
$B
[1] 5