如果有多个单词,则在逗号后提取字符串中的最后一个单词,否则第一个单词 [英] Extract last word in a string after comma if there are multiple words else the first word
本文介绍了如果有多个单词,则在逗号后提取字符串中的最后一个单词,否则第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下单词的数据
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 country name from the data. The tricky part is if i extract just the last word then I will have only one record (France).
library(stringr)
df$country<- word(df$location,-1)
关于如何从这些数据中提取国家/地区数据的任何想法?
Any ideas on how to extract country data from this data?
id location country
1 xyz, sss, New Zealand New Zealand
2 USA USA
3 Pris,France France
推荐答案
您可以尝试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"
这篇关于如果有多个单词,则在逗号后提取字符串中的最后一个单词,否则第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文