Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert a vector of strings to Title Case
    primarykey
    data
    text
    <p>I have a vector of strings in lower case. I'd like to change them to title case, meaning the first letter of every word would be capitalized. I've managed to do it with a double loop, but I'm hoping there's a more efficient and elegant way to do it, perhaps a one-liner with <code>gsub</code> and a regex. </p> <p>Here's some sample data, along with the double loop that works, followed by other things I tried that didn't work.</p> <pre><code>strings = c("first phrase", "another phrase to convert", "and here's another one", "last-one") # For each string in the strings vector, find the position of each # instance of a space followed by a letter matches = gregexpr("\\b[a-z]+", strings) # For each string in the strings vector, convert the first letter # of each word to upper case for (i in 1:length(strings)) { # Extract the position of each regex match for the string in row i # of the strings vector. match.positions = matches[[i]][1:length(matches[[i]])] # Convert the letter in each match position to upper case for (j in 1:length(match.positions)) { substr(strings[i], match.positions[j], match.positions[j]) = toupper(substr(strings[i], match.positions[j], match.positions[j])) } } </code></pre> <p>This worked, but it seems inordinately complicated. I resorted to it only after experimenting unsuccessfully with more straightforward approaches. Here are some of the things I tried, along with the output:</p> <pre><code># Google search suggested \\U might work, but evidently not in R gsub("(\\b[a-z]+)", "\\U\\1" ,strings) [1] "Ufirst Uphrase" "Uanother Uphrase Uto Uconvert" [3] "Uand Uhere'Us Uanother Uone" "Ulast-Uone" # I tried this on a lark, but to no avail gsub("(\\b[a-z]+)", toupper("\\1"), strings) [1] "first phrase" "another phrase to convert" [3] "and here's another one" "last-one" </code></pre> <p>The regex captures the correct positions in each string as shown by a call to <code>gregexpr</code>, but the replacement string is clearly not working as desired. </p> <p>If you can't already tell, I'm relatively new to regexes and would appreciate help on how to get the replacement to work correctly. I'd also like to learn how to structure the regex so as to avoid capturing a letter after an apostrophe, since I don't want to change the case of those letters. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload