Tuesday, January 22, 2008

A few string functions for working with case

##x -- a vector of single element strings
charToUpper <- function(x) {
i <- match(x, letters)
ifelse(!is.na(i), LETTERS[i], x)
}

##s -- string to be put in uppercase
upper <- function(s) {
paste(charToUpper(strsplit(s, "")[[1]]), collapse="")
}

titleCase <- function(s) {
n <- nchar(s)
if (n > 0) {
paste(charToUpper(substr(s, 1, 1)),
substr(s, 2, n), sep="")
}
else {
s
}
}
It's hard to believe these aren't defined (in native code) in the base environment. Of course, R's primary focus isn't string manipulation, but these come up naturally enough when building up labels for plots. Maybe they're worried about internationalization issues? (Or maybe I've just missed the relevant functions.)

By the way, the "mystery" over the differences between the mgfs given by C & B for negative binomial and geometric distributions is solved by noting the differences in support (x = 0, 1, ... vs. x = 1, 2, ...) for the two as defined in the book.

No comments: