别忘了避开这些点!在正则表达式模式中
.
匹配(几乎)任何字符。如果你指的是一个字面上的点,你必须用一个
\
(你还得和另一个逃走
\
所以:
df %>% mutate(street2 = str_replace(street, 'S\\.', "South"),
street2 = str_replace_all(street2, 'PKWY', "PARKWAY"),
street2 = str_replace_all(street2, 'St\\.', "Street"))
将导致
# street street2
# 1 333 S. HOPE STREET 333 South HOPE STREET
# 2 21 South Hope Street 21 South Hope Street
# 3 54 Hope PKWY 54 Hope PARKWAY
# 4 60C/O St. 60C/O Street
stringr::str_to_title
df %>% mutate(street2 = str_replace(street, 'S\\.', "South"),
street2 = str_replace_all(street2, 'PKWY', "PARKWAY"),
street2 = str_replace_all(street2, 'St\\.', "Street") ) %>%
mutate_all( ., str_to_title )
# street street2
# 1 333 S. Hope Street 333 South Hope Street
# 2 21 South Hope Street 21 South Hope Street
# 3 54 Hope Pkwy 54 Hope Parkway
# 4 60c/O St. 60c/O Street