Extract the last word in the decimal place, if there are several else words, the first word

I have data where the following words

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

I would like to extract the name of the country from the data. The hard part - if I extract only the last word, then I will have only one entry (France).

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

Any ideas on how to extract data from this data from a country?

  id location country 1 xyz, sss, New Zealand New Zealand 2 USA USA 3 Pris,France France 
+5
source share
2 answers

You can try sub

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

Or

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

stringi solution:

 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 removes unnecessary spaces before / after the country name.

0
source

All Articles