An option would be to paste
the .
at the beginning and then with str_detect
or grepl
filter
the rows
library(dplyr)
library(stringr)
df %>%
filter(str_detect(values, str_c(".", select[1]))) %>%
summarise(n = n())
# n
#1 3
Or instead of using *
, specify as .
in 'select' as .
matches any character while *
implies 0 or more characters of the character preceding.
select <- chartr('*', '.', select)
for (i in seq_along(select)){ print(df %>%
filter(str_detect(values, select[i])) %>%
summarise(n()))}
# n()
#1 3
# n()
#1 1
This would work with both grepl
and str_detect
while the OP's original string *
works only with grepl
Another option if we are using a fixed match with %in%
would be to create a logical condition
for (i in seq_along(select)){ print(df %>%
filter(if(!select[i] %in% values) TRUE else values %in% select[i]) %>%
summarise(n()))}
# n()
#1 3
# n()
#1 1