代码之家  ›  专栏  ›  技术社区  ›  Roger

拼出街道名称的方向

  •  0
  • Roger  · 技术社区  · 6 年前

    我尝试使用stringr包更正数据帧的街道名称,将“S.”拼写为“South”或“E”拼写为“East”以及“st.”拼写为“street”。样本数据如下。

    df = data.frame(street = c('333 S. HOPE STREET', '21 South Hope Street', '54 Hope PKWY', '60C/O St.'))
    

      df2 <- df %>% mutate(street2 = str_replace(street, 'S', "South"),
                         street2 = str_replace_all(street2, 'PKWY', "PARKWAY"),
                         street2 = str_replace_all(street2, 'st.', "Street"))
    

    返回以下结果。

    street              street2
    
    333 S. HOPE STREET     333 South. HOPE STREET
    21 South Hope Street   21 Southouth Hope Street
    54 Hope PKWY           54 Hope PARKWAY
    60C/O St.              60C/O Southt.
    

    这就是我想要的结果。不知道哪里出错了。

    street              street2
    
    333 S. HOPE STREET     333 South HOPE STREET
    21 South Hope Street   21 South Hope Street
    54 Hope PKWY           54 Hope PARKWAY
    60C/O St.              60C/O Sreet.
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Wimpel    6 年前

    别忘了避开这些点!在正则表达式模式中 . 匹配(几乎)任何字符。如果你指的是一个字面上的点,你必须用一个 \ (你还得和另一个逃走 \

    所以:

    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