Reputation: 59
I have a set of strings, and a set of patterns that I want to look up in the strings.
I know that the patterns exist somewhere there, I just want them to be returned in same order as mentioned in the pattern variable:
Reproducible code:
my_strings <- c("I see trees of green",
"red roses too",
"I see them blossom",
"for me and you")
my_patterns <- "blossom|green|red"
grep (my_patterns, my_strings, value = TRUE)
It returns:
[1] "I see trees of green" "red roses too" "I see them blossom"
I don't want it to return this, instead I want it to return:
[1] "I see them blossom" "I see trees of green" "red roses too"
Since this is the order they where mentioned in at my_patterns
variable.
How can I achieve this efficiently?
Thanks in advance
Upvotes: 1
Views: 607
Reputation: 1423
It does not work because you don't define patterns but one pattern which is "blosso OR green OR red".
Then, your grep
goes through your strings and return every value, in the same order, where it meets one of the 3 words.
Instead, you need to define 3 patters and loop on them, for example:
my_strings <- c("I see trees of green",
"red roses too",
"I see them blossom",
"for me and you")
my_patterns <- c("blosso","green","red")
sapply(my_patterns, function(x) grep(x, my_strings, value = TRUE))
Hope this helps!
Upvotes: 1