[R] String manipulation---mixed case

Renaud Lancelot renaud.lancelot at cirad.fr
Sun Dec 5 16:38:03 CET 2004


Damian Betebenner a écrit :
> Hello,
> 
> Does anyone know of a "slick" way to get R to convert a string which
> is all upper case to a string where the first letter in each word is
> upper case and all others are lower case?
> 
> I suspect the solution is to begin by parsing the string, convert the
> appropriate letters to upper and lower case using "toupper" and
> "tolower", and then to paste the pieces back together. Moreover,
> given the elegance and power of R, I'll bet this can be coded very
> tersely. Before I embarked on trying to code this, I thought I would
> tap the R braintrust to see if this has already been done.
> 
> Any help greatly appreciated,
> 
> Damian
> 
> Damian Betebenner Educational Research, Measurement & Evaluation 
> Lynch School of Education Boston College Chestnut Hill, MA 02467
> 
> (617) 552 4491
> 
> ______________________________________________ 
> R-help at stat.math.ethz.ch mailing list 
> https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the
> posting guide! http://www.R-project.org/posting-guide.html
> 

This question was posted a while ago and answered by Christian
Hoffmann. I wrapped it in a small function:

CapLeading <- function (string){
   fn <- function(x){
     v <- unlist(strsplit(x, split = " "))
     u <- sapply(v, function(x){
            x <- tolower(x)
            substring(x, 1, 1) <- toupper(substring(x, 1, 1))
            x})
     paste(u, collapse = " ")
     }
   sapply(string, fn)
   }

Best,

Renaud

-- 
Dr Renaud Lancelot, vétérinaire
C/0 Ambassade de France - SCAC
BP 834 Antananarivo 101 - Madagascar

e-mail: renaud.lancelot at cirad.fr
tel.:   +261 32 40 165 53 (cell)
         +261 20 22 665 36 ext. 225 (work)
         +261 20 22 494 37 (home)




More information about the R-help mailing list