'tidyr separate_rows with user defined function? (r / tidyverse)

separate_rows separate based on column values into multiple rows, repeating value of other columns.

> t <- tibble(x = c("a,b", "c,d"), v = c(1,2))
> t %>% separate_rows(x, sep = ",")
# A tibble: 4 × 2
  x         v
  <chr> <dbl>
1 a         1
2 b         1
3 c         2
4 d         2

However, what if I want to apply a function over it? after the separate for example change the value of x to true if in ("a", "b") and false otherwise.

I understand all I need to do is a mutate follow separate_rows. My question is if there is already a function that does separate and process a comma delimited value. How do I use the function in a similar way as separate_rows? (the reason is I want to separate complex split logic into a function rather than in mutate)

For example below does the logic above and return a vector of values. Is it possible perform similar operation as separate rows? (ie. split on the column and repeating row values)

proc <- function(text){
  text %>% 
    str_split(pattern = ",") %>%
    unlist() %>%
    sapply(function(x){
            if(x %in% c("a", "b")) 
              return(T) 
            else 
              return(F)
          })
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source