@dash2 has already provided what I believe is the best answer assuming you're working with country names, however, if you're looking for something more general and/or something that achieves exactly what the title of this question calls for or more closely matches your example, here's an idea...
The first/pattern
argument of gsub
is a regex, so you can match any character/s before and or after your match string by adding ".*" before and after it like this...
gsub(".*Yugoslav.*", "Macedonia", "The former Yugoslav Republic of Macedonia")
So your exact example from above, fixed to work how it sounds like you wanted would look like...
t<-as.data.frame(sapply(data, function(x) gsub(".*Yugoslav.*", "Macedonia",x)))
Note: gsub
is vectorised, i.e. it accepts a character vector for the x
argument, so there's no need to run it through sapply
. The following two commands are roughly equivalent (though sapply adds names to the result)...
sapply(data, function(x) gsub("Yugoslav", "Macedonia",x))
gsub("Yugoslav", "Macedonia", data)
So a better version of your exact example would be...
t <- as.data.frame(gsub(".*Yugoslav.*", "Macedonia", data))
Assuming you have a data frame df
with a column/vector named country
which contains strings, the following code would change (entirely) any values that contain "Yugoslav" to "Macedonia" (including strings such as "The former Yugoslav Republic of Macedonia") in the existing data frame...
df$country <- gsub(".*Yugoslav.*", "Macedonia", df$country)
You would need a separate command for each set of strings you want to swap, so I don't think this is the best way to achieve it if you have many changes to make, but maybe you were only interested in making a few changes, or maybe you want to do each one manually for some reason.