简体   繁体   中英

R: How to find grep patterns in string, in the same order as the pattern

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM