Home > Back-end >  How do you capitalize the first letter for each word in a list?
How do you capitalize the first letter for each word in a list?

Time:04-27

I want to capitalize first letter of each word in a list Here is a list of car names. For example, alfa romeo is in lower case, whilst BMW is all caps.

library(stringr)
carlist <- c("alfa romeo", "BMW", "ford")
str_to_title(carlist)

> str_to_title(carlist)
[1] "Alfa Romeo" "Bmw"        "Ford" 

I tried str_to_title but it makes all words proper case. This doesn't work as it's makes BMW lower case for the "mw". I'd like to be able to use function that converts just the first letter into caps of each word (so this leaves BMW as it is). Any help greatly appreciated. Thanks

CodePudding user response:

Using the built-in base R toTitleCase is probably the easiest, which will only convert the first letter and leave the others alone (so it won't lowercase the mw in BMW like str_to_title does).

carlist <- c("alfa romeo", "BMW", "ford")

tools::toTitleCase(carlist)

Output

[1] "Alfa Romeo" "BMW"        "Ford"  

CodePudding user response:

You can use gsub to look for word boundaries followed by any letter, then convert the matched group to upper case.

carlist <- c("alfa romeo", "BMW", "ford")

gsub("\\b([A-Za-z])", "\\U\\1", carlist, perl = TRUE)

Result:

[1] "Alfa Romeo" "BMW"        "Ford"      

CodePudding user response:

Using dplyr and stringr:

if_else(carlist == str_to_upper(carlist), carlist, str_to_title(carlist))

Producing

[1] "Alfa Romeo" "BMW"        "Ford"

Since it only applies str_to_title to strings which do not match their uppercase. Note that this won't work if you have elements like bmw. One way around that could be to set a length (probably 3) to decide which strings are abbreviations and which are not.

  •  Tags:  
  • r
  • Related