2

I want to capitalise every word of a sentence except the very first letter. There is a similar discussion here - Capitalize the first letter of both words in a two word string

So the function can be used as -

name <- c("zip code", "state", "final count")
simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
      sep="", collapse=" ")
}
sapply(name, simpleCap)

But it also capitalise the first letter as well. I want something like "zip Code" instead "Zip Code". Is there any way to achieve this?

Any help will be highly appreciated.

Bogaso
  • 2,838
  • 3
  • 24
  • 54

3 Answers3

3

I like the second solution in that link using toTitleCase. You can use regex to make the first character lower-case.

simpleCap <- function(x) {
  sub('(.)', '\\L\\1', tools::toTitleCase(x), perl = TRUE)
}

simpleCap('Zip Code')
#[1] "zip Code"
simpleCap('this text')
#[1] "this Text"
simpleCap(name)
#[1] "zip Code"    "state"       "final Count"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

Or with slight modification of the strsplit approach:

capExceptFirst <- function(x) {
  s <- strsplit(x, " ")[[1]]
  
  paste(
    tolower(s[1]),
    paste(toupper(substring(s[-1], 1,1)), substring(s[-1], 2),
        sep="", collapse=" "),
    collapse = " "
  )
}

sapply(name, capExceptFirst)

Output:

     zip code         state   final count 
   "zip Code"      "state " "final Count" 
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
2

With some basic regex:

name <- c("zip code", "state", "final count")
gsub("\\s([a-z])", " \\U\\1", name, perl = TRUE)
# [1] "zip Code"     "state"        "final Count"

To allow for non-ascii letters:

name <- c("zip code", "state", "final count", "uribe álvaro")
gsub("\\s(\\p{L})", " \\U\\1", name, perl = TRUE)
# [1] "zip Code"     "state"        "final Count"  "uribe Álvaro"
s_baldur
  • 29,441
  • 4
  • 36
  • 69