Fixing case problems
Finally, you might want to transform strings to a common case. You've seen you can use str_to_upper()
and str_to_lower()
, but there is also str_to_title()
which transforms to title case, in which every word starts with a capital letter.
This is another situation where stringi
functions offer slightly more functionality than the stringr
functions. The stringi
function stri_trans_totitle()
allows a specification of the type
which, by default, is "word"
, resulting in title case, but can also be "sentence"
to give sentence case: only the first word in each sentence is capitalized.
Try outputting the catcidents
in a consistent case.
This exercise is part of the course
String Manipulation with stringr in R
Exercise instructions
A character vector of cat-related accidents has been pre-defined in your workspace as catcidents
.
- Store the first five elements of
catcidents
ascat5
. - Use
writeLines()
to displaycat5
. - Repeat but now pass
cat5
transformed to title case withstr_to_title()
. - Try again using
stri_trans_totitle()
instead. This should be identical tostr_to_title()
. - Finally, display the first 5 elements of
cat5
transformed to sentence case, by passing thetype
argument tostri_trans_totitle()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(stringi)
# Get first five catcidents
cat5 <- ___
# Take a look at original
___
# Transform to title case
___
# Transform to title case with stringi
___
# Transform to sentence case with stringi
___