如果第一个单词还有多个单词,则在逗号后面的字符串中提取最后一个单词

use*_*187 6 r string-matching stringr stringi

我有数据的地方如下

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

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

library(stringr)
df$country<- word(df$location,-1)
Run Code Online (Sandbox Code Playgroud)

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

 id  location                      country
  1   xyz, sss, New Zealand        New Zealand
  2   USA                          USA
  3   Pris,France                  France
Run Code Online (Sandbox Code Playgroud)

akr*_*run 10

你可以试试 sub

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

要么

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

  • `explain [sub]:`from`df $ location`,替换任何字符`.`,发生任何次数`*`,最多逗号,后跟任何数字/类型的空格`\\ s`什么都没有` ''``'解释[str_extract]:`来自`df $ location`,提供1个或多个`+`整个单词`\\ b`,而不是以逗号`^,`结尾的字符串中的`[]`直到`字符串`$`的结尾.(所以基本上,用逗号后的所有单词提供) (4认同)