Skip to content

Instantly share code, notes, and snippets.

@chris-prener
Created November 27, 2018 22:32
Show Gist options
  • Save chris-prener/891df24b369c8be68c0c13ed726f7130 to your computer and use it in GitHub Desktop.
Save chris-prener/891df24b369c8be68c0c13ed726f7130 to your computer and use it in GitHub Desktop.
Detecting Multiple Patterns in Strings, Iteration
library(dplyr)
library(stringr)
# create test data
orders <- data.frame(
id = c(1,2,3,4),
items = c("Apples and Turkey", "Bacon and Crackers", "Bananas and Juice", "Pecan Pie and Ice Cream"),
stringsAsFactors = FALSE
)
# define primary function
fruitLoop <- function(.data, var){
# save parameters to list
paramList <- as.list(match.call())
# nse
if (!is.character(paramList$var)) {
varQ <- rlang::enquo(var)
} else if (is.character(paramList$var)) {
varQ <- rlang::quo(!! rlang::sym(var))
}
# create vector through iteration
out <- dplyr::mutate(.data, fruit = purrr::map_lgl(!!varQ, isFruit))
# return output
return(out)
}
# define sub function
isFruit <- function(x){
# create pattern vector
patternVector <- c("Apples", "Pears", "Bananas")
# iterate over items in pattern vector
patternVector %>%
base::split(patternVector) %>%
purrr::map_lgl( ~ stringr::str_detect(string = x, pattern = .x)) %>%
base::any(.) -> out
# return output
return(out)
}
# test function with both quoted and unquoted inputs
fruitLoop(orders, items)
fruitLoop(orders, "items")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment