0

I have a dataframe and I would like to add a column with matched patterns which I have stored in a list, something like this:

This is my dataframe:

order_lines <- tibble(
  order_number = c(100, 200, 300, 400, 500, 600),
  description = c("xyz", "axyz", "abc", "wabc", "abcla", "ggg")
)

And this is the list with the pattern I want to look for in order_lines$description:

ref <- list("xyz", "abc")

I have created a function to do that:

extractor <- function(df, pat){
  df <- df %>%
        mutate(references = str_extract(string = description, pattern = pat))
  df
}

But when I run extractor(df = order_lines, pat = ref) what I got is the next error: 'Error in mutate_impl(.data, dots) : Evaluation error: no applicable method for 'type' applied to an object of class "list".'

When I first came across with the problem I thought that'd be easy to solve because I figured out that was something wrong about using a list with dplyr::mutate. I still believe the list is involved but I do not know how to fix it.

I do not know if session info is useful in this case:

R version 3.4.4 (2018-03-15) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.1 LTS

Thanks in advance.

1 Answers1

0

Finally I have found a solution by removing mutate from the function and using $ instead. This is the new function:

extractor <- function(df, pat) {
  df$references <- str_extract(string = description, pattern = pat))
  df
}

Then I have used purrr::map to apply the function to every element of my list ref, that is:

ref %>%
  map(extractor, df = order_lines)

I hope this will help someone in the future.