Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you capitalize the first letter for each word in a list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"      
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading