2016-08-02 74 views
2

我想在一组可能略有不同的字符串上使用gsub;R gsub多个条件

I went to the store last night 
I went to the park yesterday 
I went to starbucks this morning 

我需要使用GSUB来代替“我去......”,但有时会有一个“的”,有时也不会

这样的事情,但以下将无法正常工作

gsub('i went to [the|a-z]','REPLACED',string) 

REPLACED last night 
REPLACED yesterday 
REPLACED this morning 
+0

像这样的东西? 'gsub(“我去了*(store | park | starbucks)”,“REPLACED”,data)' – FisherDisinformation

+0

@ user2100721他把它放在我相信的第二个代码块中。 – FisherDisinformation

+0

@ user2100721它在第二个块中。谢谢 – chattrat423

回答

0

您可以使用stringr包与弗洛荣正则表达式(在使用^字符串的前挂靠):

library(stringr) 
sentences <- c("I went to the store last night", 
       "I went to the park yesterday", 
       "I went to starbucks this morning") 
str_replace(sentences, "^I went to(the)?", "REPLACED") 
# [1] "REPLACED store last night"  "REPLACED park yesterday"   
# [3] "REPLACED starbucks this morning" 

如果有多个实例相同的字符串内更换,你可能想省略^和使用str_replace_all()