Named variables within purrr::map2

I am using map2 to iterate through a function:

library(tidyverse)
x <- list(1, 1, 1)
y <- list(10, 20, 30)
addition <- function(num_1, num_2){
  num_1 + num_2}
map2(.x=x, .y=y, .f=addition)
map2(num_1=x, num_2=y, .f=addition)

The version where I do .x=x and .y=y works but when I name the variables num_1=x and num_2=y, it doesnt work.

Is it possible to have named variables within map2? I concerned that the .x and .y could get mixed up leading to unanticipated outcomes.

short answer no; map2 takes .x and .y and then you can choose how they are applied into addition , though the default is .x first and .y second.

on the other hand, R lets you freely write your own functions, so you can do

library(tidyverse)
x <- list(1, 1, 1)
y <- list(10, 20, 30)

addition <- function(num_1, num_2){
  num_1 + num_2}

mymap2 <- function(num_1,num_2,.f){
  map2(.x=num_1,
       .y=num_2,
       .f=.f)
}
mymap2(num_1=x,
       num_2=y,
       addition)

any mymap2 will use num_1 and num_2 as the symbols instead of .x, and .y
but I doubt the benefits are worth the costs.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.