Created
November 27, 2018 22:32
-
-
Save chris-prener/a3737fc06f0a067138b5bc63348a0eb6 to your computer and use it in GitHub Desktop.
Detecting Multiple Patterns in Strings, Vectorized
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
) | |
# create reference | |
fruit <- c("Apples", "Pears", "Bananas") | |
# return expected results | |
orders %>% | |
mutate(fruit = suppressWarnings(str_detect(items, pattern = fruit))) | |
# express as a 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 pattern vector | |
patternVector <- c("Apples", "Pears", "Bananas") | |
# create logical vector | |
.data %>% | |
dplyr::mutate(fruit = suppressWarnings(stringr::str_detect(!!varQ, pattern = patternVector))) -> 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