Re: [R] Applying "toupper" to only portions of text strings

From: peter dalgaard <>
Date: Fri, 27 May 2011 00:23:36 +0200

On May 27, 2011, at 00:05 , Dennis Fisher wrote:

> Colleagues
> Assume that I have a vector containing some text strings, some of which contain a particular character. I could like to apply "toupper" to the text before the character. For example (in this case, "|" is the particular character):
> TEXT <- c("aaaa", "bbb|cc", "|ddd")
> TEXT <- c("AAAA", "BBB|cc", "|dddd")

How are you going to get that extra d in there? >;-)

> I could loop through each element, strsplit at the character, apply toupper to the first component, then paste each element together. But, I hope that there is a simpler means to accomplish this.

No, I think that is pretty much the plan. It's a one-liner, though:

> sapply(strsplit(TEXT,"|",

fixed=T),function(x){paste(c(toupper(x[1]),x[-1]),collapse="|")}) [1] "AAAA" "BBB|cc" "|ddd"

OK, a _long_ one-liner...

Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email:  Priv:

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 26 May 2011 - 22:29:21 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 26 May 2011 - 22:30:10 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive