regexrcapitalization

R: Capitalizing everything after a certain character


I would like to capitalize everything in a character vector that comes after the first _. For example the following vector:

x <- c("NYC_23df", "BOS_3_rb", "mgh_3_3_f") 

Should come out like this:

"NYC_23DF" "BOS_3_RB" "mgh_3_3_F"

I have been trying to play with regular expressions, but am not able to do this. Any suggestions would be appreciated.


Solution

  • You were very close:

    gsub("(_.*)","\\U\\1",x,perl=TRUE)
    

    seems to work. You just needed to use _.* (underscore followed by zero or more other characters) rather than _* (zero or more underscores) ...

    To take this apart a bit more:

    For more details, search for "replacement" and "capitalizing" in ?gsub (and ?regexp for general information about regular expressions)