我有一组字符串,以及一组要在字符串中查找的模式。
我知道模式存在于某处,我只希望它们按照模式变量中提到的相同顺序返回:
可复制的代码:
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)
它返回:
[1]“我看到绿色的树木”“也看到红色的玫瑰”“我看到它们开花”
我不希望它返回此值,而是希望它返回:
[1]“我看到它们开花”“我看到绿色的树木”“也看到红色的玫瑰”
由于这是它们在my_patterns
变量中提到的顺序。
如何有效地做到这一点?
提前致谢
它不起作用,因为您没有定义模式,而是定义了一种模式“ blosso或green或red”。然后,您grep
遍历字符串并以相同的顺序返回每个值,该值与三个单词之一相遇。
相反,您需要定义3个模式并在其上循环,例如:
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))
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句