Aaron
Aaron

Reputation: 111

Using grep to find two letters in specific order in R

To get started

words <- c("bait", "gait","quit","suit","wait","spit","twit") 

I would like to write a grep() function that returns words that rhyme with "it" ... in this case it would return:

"quit", "spit", and "twit"

but not

"bait", "suit", or "wait"

So far I am stuck on one that fails to distinguish:

grep("[^a][i][t]$", words, value = T) 

And another that erroneously removes "quit"

grep("[^su|a][i][t]$", words, value =T )

I'm sure there is an easy out here, but I'm not seeing it. Thanks!

Upvotes: 1

Views: 219

Answers (1)

G5W
G5W

Reputation: 37641

I think that you want to specify that a final 'it' is either preceded by a consonant (non-vowel) or by 'qu'. So ...

grep("(qu|[^aeiou])it$", words, value=T)
[1] "quit" "spit" "twit"

Upvotes: 3

Related Questions