Reputation: 343
I'm new to regexs and trying to replace entire words based on the first two characters of a string. For example, if I have a data frame called automobiles and a variable called cars, I'd like to replace Honda with Japanese. I can get it to replace the first two characters but not the entire word. Based on what I read on here, here is what I came up with, but it's not working. What am I doing wrong?
automobiles$cars <- gsub(ignore.case=TRUE, "\\<^ho\\>", paste("ho", "Japanese"), automobiles$cars)
Upvotes: 0
Views: 102
Reputation: 2885
This is how you replace all strings starting with "Ho" with "Japanese:
> cars <- c("Honda", "Audi", "Ford")
> cars
[1] "Honda" "Audi" "Ford"
> cars <- gsub("^Ho(.*)", "Japanese", cars, ignore.case = TRUE)
> cars
[1] "Japanese" "Audi" "Ford"
Your code contains some very strange stuff, so I suspect that your data/question might be more complex than that. Please explain further if that is the case.
The catch is ^Ho(.*)
, which selects the complete string ((.*)
is for "everything that follows") if the string starts (^
) with "Ho
".
Upvotes: 2