[R] Applying "toupper" to only portions of text strings
peter dalgaard
pdalgd at gmail.com
Fri May 27 00:23:36 CEST 2011
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):
>
> ORIGINAL:
> TEXT <- c("aaaa", "bbb|cc", "|ddd")
>
> AFTER APPLICATION OF toupper:
> 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: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list