Search code examples
rregexcase-sensitiveuppercasestringr

Upper case cardinal directions, use title case for everything else in R


I have a huge list of addresses that are all uppercase. I would like to convert to title case, but preserve the uppercase for the cardinal directions, e.g. NE, NW, SE, SW.

address <- c("14615 SE CREEKSIDE DRIVE")
stringr::str_to_title(address)

# this returns 
14615 Se Creekside Drive

# desired result
14615 SE Creekside Drive

Solution

  • With str_replace you can convert back the cardinal directions. Spaces included to avoid cardinals appearing in names, but if they might be surrounded by things other than spaces you'll have to modify this.

    library(stringr)
    addresses <- c("14615 SE CREEKSIDE DRIVE", "14615 NW CREEKSIDE DRIVE", "14615 SE SEASIDE DRIVE", "14615 SE TANWELL DRIVE")
    
    addresses %>%
      str_to_title %>%
      str_replace(" (N|S)(e) ", " \\1E ") %>%
      str_replace(" (N|S)(w) ", " \\1W ")
    #> [1] "14615 SE Creekside Drive" "14615 NW Creekside Drive"
    #> [3] "14615 SE Seaside Drive"   "14615 SE Tanwell Drive"
    

    Created on 2018-06-26 by the reprex package (v0.2.0).