Reputation: 13
I was wondering if anyone had come across a solution to this problem when cleaning up data in R. The idea is to have a list of strings for example:
strings = c("hello world", "goodbye all", "help is appreciated", "hello sam")
then we would go through the list of strings and whenever a certain word is found the entire string would be replaced.
Therefore if we are looking for the word "hello" it would be replaced with "math"
so the output I would be looking for would be:
"math", "goodbye all", "help is appreciated", "math".
Any help or ideas are appreciated.
Upvotes: 1
Views: 43
Reputation: 269654
Try this:
sub(".*hello.*", "math", strings)
giving:
[1] "math" "goodbye all" "help is appreciated"
[4] "math"
Upvotes: 1
Reputation: 173577
Just use grepl
:
strings = c("hello world", "goodbye all", "help is appreciated", "hello sam")
> strings[grepl("hello",strings)] <- "math"
> strings
[1] "math" "goodbye all" "help is appreciated" "math"
Upvotes: 4