[R] lower/upper case question

Gabor Grothendieck ggrothendieck at gmail.com
Fri Dec 17 22:55:30 CET 2010

On Fri, Dec 17, 2010 at 4:38 PM, William Dunlap <wdunlap at tibco.com> wrote:
> Also, gsub() can change the case of part a string --
> use perl=TRUE and \\U or \\L (and perhaps \\E) in
> the replacement string.  E.g., capitalize color names
> with
>  > gsub(paste(sep="", "(", paste(colors(),collapse="|"), ")"),
>    "\\U\\1",
>    "The quick red Fox jumped over the lazy brown Dog",
>    perl=TRUE)
>  [1] "The quick RED Fox jumped over the lazy BROWN Dog"

Nice example. Here are two ways to do it with gsubfn:

phrase <- "The quick red Fox jumped over the lazy brown Dog"

# 1
gsubfn("\\w+", ~ if (tolower(x) %in% colors()) toupper(x) else x, phrase)

# 2
# Colors is a list with lower case values and upper case names
# Unlike the last one this will not capitalize mixed case, only lower

Colors <- as.list(setNames(toupper(colors()), colors()))
gsubfn("\\w+", Colors, phrase)

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list