The objective is to parse a regular expression and replace the matched pattern.
Consider this example:
data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
I have to locate all occurrences of cat
and a number [0-9]
. To do this:
found <- data[grepl("(^cat.[a-z][0-9])|(^cat.[0-9])",data)]
found
[1] "cat 6kg" "cat g250" "cat 10 kg"
The next step is to replace each element of found
with string cat
. I have attempted gsub, sub, and gsubfn() from package (gsubfn) according to Stack question 20219311:
gsubfn("((^cat.[a-z][0-9])|(^cat.[0-9]))", "cat",data)
[1] "catkg" "cat50" "cat dog" "cat0 kg"
which is NOT the expected result:
[#] "cat" "cat" "cat dog" "cat"
I think I'm missing a point. I would appreciate any help I could get. Thanks.
Try this:
You could also do
Or
Simple,,,, Just assign the string
cat
to the match elements. This will replace all the chars present in the element withcat
or