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
>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"