Reputation:
I’m using filter to my dataset to select certain values from column:
%>%
filter(col1 %in% c(“value1”, “value2"))
How ever I don’t understand how to filter values in column with pattern without fully writing it. For example I also want all values which start with “value3” (“value33”, “value34”,....) along with “value1” and “value2”. Can I add grepl to that vector?
Upvotes: 0
Views: 464
Reputation: 389047
Here are few options in base R :
Using grepl
:
subset(df, grepl('^value', b))
# a b
#1 1 value3
#3 3 value123
#4 4 value12
Similar option with grep
which returns index of match.
df[grep('^value', df$b),]
However, a faster option would be to use startsWith
subset(df, startsWith(b, "value"))
All of this would select rows where column b
starts with "value"
.
data
df <- data.frame(a = 1:5, b = c('value3', 'abcd', 'value123', 'value12', 'def'),
stringsAsFactors = FALSE)
Upvotes: 0
Reputation: 206253
If you want to use another tidyverse package to help, you can use str_starts
from stringr
to find strings that start with a certain value
dd %>% filter(stringr::str_starts(col1, "value"))
Upvotes: 2
Reputation: 1180
You can use regular expressions to do that:
df %>%
filter(str_detect('^value[1-3]'))
Upvotes: 3