[R] String manipulation---mixed case

Gabor Grothendieck ggrothendieck at myway.com
Mon Dec 6 12:47:10 CET 2004


Martin Maechler <maechler <at> stat.math.ethz.ch> writes:

: 
: >>>>> "Spencer" == Spencer Graves <spencer.graves <at> pdf.com>
: >>>>>     on Sun, 05 Dec 2004 13:48:07 -0800 writes:
: 
:     Spencer> That's great, Peter. 
:     Spencer> For pedestrians like me who are not quite as facile with 
regular 
:     Spencer> expressions, the following seems slightly more readable: 
: 
:     Spencer> s <- "the quick red fox jumps over the lazy brown dog"
:     Spencer> ss <- strsplit(s, " ")[[1]]
:     Spencer> ss1 <- substring(ss, 1,1)
:     Spencer> ss2 <- substring(ss, 2)
:     Spencer> paste(toupper(ss1), ss2, sep="", collapse=" ")
: 
:     Spencer> [1] "The Quick Red Fox Jumps Over The Lazy Brown Dog"
: 
: Nice.  Since this has been asked before,
: and it is something common enoguh that Emacs even has this on a
: key (M-c), I think it's worth making a small example on the help
: page for toupper/tolower:
: 
: ## "Mixed Case" Capitalizing Function :
: capitalize <- function(x) {
:   ## toupper( every first letter of a word ) :
:   s <- strsplit(x, " ")[[1]]
:   paste(toupper(substring(s, 1,1)), substring(s, 2), sep="", collapse=" ")
: }
: capitalize("the quick red fox jumps over the lazy brown dog")
: ## ->  [1] "The Quick Red Fox Jumps Over The Lazy Brown Dog"

or the following variation which is about the same length but
also (1) handles vectors of strings and (2) does not depend
on the input being lower case:


capwords <- function(s) {
	capword <- function(s) 
		paste( toupper(substring(s,1,1)), tolower(substring(s,2)), 
			sep = "", collapse = " ")
	sapply(s, capword, USE.NAMES = !is.null(names(s)))
}




More information about the R-help mailing list