chattrat423 chattrat423 - 1 year ago 231
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 Source


gsub("I went to (the )?[a-z]", "REPLACED", string)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download