s-news
[Top] [All Lists]

Title Case Function

To: s-news@wubios.wustl.edu
Subject: Title Case Function
From: Karen_Byron@bd.com
Date: Fri, 12 May 2006 08:51:23 -0400

I would like a function that does the following:
*    takes a character vector as an input
*   converts any periods or underscores to spaces, and
*   returns the vector in title case, i.e. the first letter of each word capitalized

I have written a function that does the above for a single string.  The vectorization is not straight forward and I suspect there are more efficient ways of doing it.  


titleCase <- function(str, change.to.space = c('.', '_'), leave.cap.alone = F){
        # seperate and convert to spaces
        n.str <- nchar(str)
        str.sep <- unlist(unpaste(str, width = 1, first = 1:n.str, sep = ''))
        for(iChange in seq(along = change.to.space)){
                str.sep <- replace(str.sep, str.sep == change.to.space[iChange], ' ')
        }

        # create index for capitalization
        cap.index <- c(na.exclude((1:length(str.sep))[match(str.sep, ' ') == 1])) + 1
        if(cap.index[1] != 1) cap.index <- c(1, cap.index)
        if(rev(cap.index)[1] > n.str) cap.index <- rev(cap.index)[-1]

        # create title case
        str.sep[cap.index] <- upperCase(str.sep[cap.index])
        if(!leave.cap.alone) str.sep[-cap.index] <- lowerCase(str.sep[(1:n.str)[-cap.index]])
        str.out <- paste(str.sep, collapse = '')

        return(str.out)
}

str.test <- 'test.me.please and test_SOME_More'
titleCase(str.test)
titleCase(str.test, change.to.space = '.')
titleCase(str.test, change.to.space = ',')
titleCase(str.test, change.to.space = NULL)
titleCase(str.test, leave.cap.alone = T)


All input appreciated.  I will post a summary to the list.
Thanks, Karen




**************************************************
IMPORTANT MESSAGE FOR RECIPIENTS IN THE U.S.A: This message may
constitute an advertisement of BD group's products or services or a
solicitation of interest in them. If this is such a message and
you would like to opt out of receiving future advertisements or
solicitations from this BD group, please forward this e-mail to the
optoutbygroup@bd.com.
**************************************************
This message (which includes any attachments) is intended only for
the designated recipient(s). It may contain confidential or
proprietary information and may be subject to attorney-client
privilege or other confidentiality protections. If you are not a
designated recipient, you may not review, use, copy or distribute
this message. If you received this in error, please notify the
sender by reply e-mail and delete this message. Thank You
**************************************************
Corporate Headquarters Mailing Address: BD (Becton, Dickinson and
Company) 1 Becton Drive Franklin Lakes, NJ 07417 U.S.A.

<Prev in Thread] Current Thread [Next in Thread>