Charles_de_Montigny
Charles_de_Montigny

Reputation: 69

How to do map2_if or pmap_if in purrr

I am trying to map over a function with multiple arguments and at the same time only apply the function based on a condition with the purrr package. I can map over multiple argument with map2 or the pmap function and I can map based on a condition with the map_if function.

The following code is an basic example of what I want to do but the function map2_if doesn't exist yet. I know that for this specific problem there is a way to solve it without functional programming but my goal is to apply it to more complex functions.

x = rnorm(n = 5, mean = 0, sd = 1)
y = rnorm(n = 5, mean = 1, sd = 2)

func = function(x, y){x + y}

map2_if(.x = x, .y = y, .p = (x > 0 & y > 0), func)

Upvotes: 2

Views: 1027

Answers (1)

alistaire
alistaire

Reputation: 43354

map2_if can't really exist, because map_if returns the element unchanged if it doesn't satisfy the predicate, and if there are two inputs, what map2_if should return if the predicate is not satisfied is unclear.

Instead, it's simpler to put the data in a data frame and break the task down into steps:

library(tidyverse)
set.seed(0)

data_frame(x = rnorm(n = 5, mean = 0, sd = 1),
           y = rnorm(n = 5, mean = 1, sd = 2)) %>% 
    filter(x > 0, y > 0) %>% 
    mutate(z = map2_dbl(x, y, `+`))
#> # A tibble: 3 x 3
#>           x         y        z
#>       <dbl>     <dbl>    <dbl>
#> 1 1.3297993 0.4105591 1.740358
#> 2 1.2724293 0.9884657 2.260895
#> 3 0.4146414 5.8093068 6.223948

If func is vectorized (like +), you don't even really need map2_dbl.

Upvotes: 7

Related Questions