Alexey Ferapontov
Alexey Ferapontov

Reputation: 5169

R: is capitalize working properly

Is "my" capitalize working properly? Here's a test case from the inside-r.org with their result in comment:

library(Hmisc)
words <- strsplit("Hello wOrld", " ")[[1]];
cat(paste(toupper(words), collapse=" "), "\n")      # "HELLO WORLD"
cat(paste(tolower(words), collapse=" "), "\n")      # "hello world"
cat(paste(capitalize(words), collapse=" "), "\n")   # "Hello WOrld"

And here's what I get:

HELLO WORLD 
hello world 
Hello wOrld  #WRONG!!!

Another test case:

> capitalize(c("Hello world", "hello world", "hello World"))
[1] "Hello world" "Hello world" "hello World"

Case 3 is wrong again. I.e. if capitalize in my case sees a capital letter anywhere in string, it doesn't work properly. Any ideas?

Update. Problem solved with R.utils

library(R.utils)
capitalize(c("Hello world", "hello world", "hello World", "test cAse"))
[1] "Hello world" "Hello world" "Hello World" "Test cAse"  

Upvotes: 1

Views: 272

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 109874

I'm not sure what you're after but this my crack at what I think you're after. it might be better to describe your goal or provide desired output. Here is a regex way to capitalize only the first letter of first word as well as capitalize every word' first letter:

x <- c("Hello world", "hello world", "hello World", "test cAse")

sub("(\\w)(\\w*)", "\\U\\1\\E\\2", x, perl=TRUE) 
## [1] "Hello world" "Hello world" "Hello World" "Test cAse"

gsub("(\\w)(\\w*)", "\\U\\1\\E\\2", x, perl=TRUE) 
## [1] "Hello World" "Hello World" "Hello World" "Test CAse"

Upvotes: 1

shadow
shadow

Reputation: 22293

You have to use lower case strings for capitalize to work. An easy workaround is to use tolower in addition to capitalize.

capitalize(tolower(c("Hello world", "hello world", "hello World")))
## [1] "Hello world" "Hello world" "Hello world"

Upvotes: 2

Related Questions