Question

I have a bunch of strings with a hyphen in it. I want to remove the hyphen and convert the following letter to lower case while keeping all the other letters intact. How do you accomplish task in R?

test <- "Kwak Min-Jung"
gsub(x=test,pattern="-(\\w)",replacement="\\1")
# [1] "Kwak MinJung"  , Not what I want
# I want it to convert to  "Kwak Minjung"
Was it helpful?

Solution

Try this:

> gsub("-(\\w)", "\\L\\1", test, perl = TRUE)
[1] "Kwak Minjung"

or this:

> library(gsubfn)
> gsubfn("-(\\w)", tolower, test)
[1] "Kwak Minjung"

OTHER TIPS

Use \\L or \\U to change the case in the replacement argument. You can use \\E to end the effect of the case conversion.

gsub(x=test,pattern="-(\\w)",replacement="\\L\\1", perl=TRUE)
# [1] "Kwak Minjung"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top