Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purrr map multiple functions and two inputs

I am trying to use purrr to map multiple functions to two inputs. An example is given below but ideally i'd like to extend this to more functions. When trying to do this i'm getting an error that the input is not found, however, even when I try and name inputs in the list of functions this doesn't rectify the problem.

library(yardstick)
library(tidyverse)

funcs <- list(accuracy = yardstick::accuracy_vec,
              recall = yardstick::recall_vec)

n <- 1000
x <- as.factor(rbinom(n, 1, 0.5))
y <- as.factor(rbinom(n, 1, 0.5))

df <- tibble(true = rep(list(y), 3),
             preds = rep(list(x), 3))

df
#> # A tibble: 3 x 2
#>   true          preds        
#>   <list>        <list>       
#> 1 <int [1,000]> <int [1,000]>
#> 2 <int [1,000]> <int [1,000]>
#> 3 <int [1,000]> <int [1,000]>

df %>% map2_df(.x = true, .y = preds, .f = funcs)
#> Error in map2(.x, .y, .f, ...): object 'true' not found

funcs <- list(accuracy = ~yardstick::accuracy_vec(truth = .x, estimate = .y),
              recall = ~yardstick::recall_vec(truth = .x, estimate = .y))

df %>% map2_df(.x = true, .y = preds, .f = funcs)
#> Error in map2(.x, .y, .f, ...): object 'true' not found

Ideally I would end up with something like this:

# A tibble: 3 x 4
  true          preds         accuracy recall
  <list>        <list>           <dbl>  <dbl>
1 <int [1,000]> <int [1,000]>      0.7    0.8
2 <int [1,000]> <int [1,000]>      0.7    0.8
3 <int [1,000]> <int [1,000]>      0.7    0.8

Any help is much appreciated, TIA

like image 942
Oska Fentem Avatar asked Jul 01 '26 21:07

Oska Fentem


1 Answers

You can use nested maps:

df %>% 
  mutate(map2_dfr(true, preds, ~map_dfc(funcs, do.call, list(.x, .y))))
like image 192
Robin Gertenbach Avatar answered Jul 03 '26 12:07

Robin Gertenbach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!