Home > front end >  filter .x before passing to function ~
filter .x before passing to function ~

Time:09-28

I have a snippet within a purrr and dplyr chain:

MAPE180 = map_dbl(TestData, ~Metrics::mape(.x %>% filter(TENURE == 180) %>% pull(CUMULATIVE_AMOUNT), 
                                           .x %>% filter(TENURE == 180) %>% pull(Prediction)))

This works fine. I wanted to remove the duplication of .x %>% filter(TENURE == 180) and tried this hoping for equivalent:

MAPE180 = map_dbl(TestData %>% filter(TENURE == 180), ~Metrics::mape(.x$CUMULATIVE_AMOUNT, .x$Prediction))

But this gives error message:

Error: Problem with `mutate()` column `MAPE180`.
ℹ `MAPE180 = map_dbl(...)`.
x no applicable method for 'filter' applied to an object of class "list"

How can I filter my .x before passing to tilde ~?

CodePudding user response:

Based on the error showed, it is filter applied on a list, which doesn't work. Instead, do the filter on each element of the list once, instead of twice

library(purrr)
library(dplyr)
map_dbl(TestData, ~ {
          tmp <- .x %>% 
                filter(TENURE == 180) # do filter once
          Metrics::mape(tmp %>% 
                          pull(CUMULATIVE_AMOUNT), 
                                           tmp %>% 
                          pull(Prediction))
    })

In addition, this can be also done within summarise

map_dfr(TestData, ~ .x %>%
                filter(TENURE == 180) %>%
                summarise(MAPE = Metrics::mape(CUMULATIVE_AMOUNT, 
                     Prediction)))
  • Related