【问题标题】:Extract last word in a string after comma if there are multiple words else the first word如果有多个单词,则在逗号后提取字符串中的最后一个单词,否则提取第一个单词
【发布时间】:2015-06-30 21:27:51
【问题描述】:

我有数据里的话如下

 location<- c("xyz, sss, New Zealand", "USA", "Pris,France")
 id<- c(1,2,3)
 df<-data.frame(location,id)

我想从数据中提取国家名称。棘手的部分是,如果我只提取最后一个单词,那么我将只有一条记录(法国)。

library(stringr)
df$country<- word(df$location,-1)

关于如何从这些数据中提取国家数据的任何想法?

 id  location                      country
  1   xyz, sss, New Zealand        New Zealand
  2   USA                          USA
  3   Pris,France                  France

【问题讨论】:

    标签: r string-matching stringr stringi


    【解决方案1】:

    你可以试试sub

     df$country <- sub('.*,\\s*', '', df$location)
     df$country
     #[1] "New Zealand" "USA"         "France"   
    

    或者

     library(stringr)
     str_extract(df$location, '\\b[^,]+$')
     #[1] "New Zealand" "USA"         "France"     
    

    【讨论】:

    • explanation [sub]: 来自df$location,替换任何字符.,出现任意次数*,最多为一个逗号,后跟任意数量/类型的空格\\s,没有@ 987654329@ explanation [str_extract]: 来自 df$location,提供 1 个或多个 + 整个单词 \\b,而不是在以逗号结尾的字符串中的 [ ] ^, 直到字符串结尾 $。 (所以基本上,提供逗号后的所有单词)
    【解决方案2】:

    stringi解决方案:

    require(stringi)
    location<- c("xyz, sss, New Zealand", "USA", "Pris,France")
    stri_trim(stri_match_first_regex(location, "(^|,)([^,]*?)$")[,3])
    ## [1] "New Zealand" "USA"         "France"  
    

    stri_trim 删除国家名称前后不必要的空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多