chattrat423 chattrat423 - 4 months ago 44
R Question

R gsub multiple conditions

I am trying to use gsub on a set of strings that might all vary in the wording slightly;

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


I need to use gsub to replace the 'I went to...', but sometimes it will have a 'the' and sometimes it won't

Something like this, but the following won't work properly

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

REPLACED last night
REPLACED yesterday
REPLACED this morning

Answer

Try:

gsub("I went to (the )?[a-z]", "REPLACED", string)