8

我的数据如下

 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
4

2 回答 2

11

你可以试试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"     
于 2015-06-30T21:28:50.543 回答
1

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删除国家名称前后不必要的空格。

于 2018-01-16T15:55:22.730 回答