r - 如何识别字符串中提到的所有国家名称并进行相应拆分?
问题描述
我有一个包含国家和其他地区名称的字符串。我只对国家名称感兴趣,理想情况下希望添加几列,每列都包含字符串中列出的国家名称。以下是数据框 lis 设置方式的示例代码:
df <- data.frame(id = c(1,2,3),
country = c("Cote d'Ivoire Africa Developing Economies West Africa",
"South Africa United Kingdom Africa BRICS Countries",
"Myanmar Gambia Bangladesh Netherlands Africa Asia"))
如果我只用空格分割字符串,那些包含空格的国家会丢失(例如“英国”)。看这里:
df2 <- separate(df, country, paste0("C",3:8), sep=" ")
因此,我尝试使用 world.cities 数据集查找国家/地区名称。但是,这似乎只在字符串中循环,直到出现非国家名称。看这里:
library(maps)
library(stringr)
all_countries <- str_c(unique(world.cities$country.etc), collapse = "|")
df$c1 <- sapply(str_extract_all(df$country, all_countries), toString)
我想知道是否可以将空格用作分隔符但定义例外(如“英国”)。这显然可能需要一些手动工作,但对我来说似乎是最可行的解决方案。有谁知道如何定义此类异常?我当然也愿意并感谢任何其他解决方案。
更新:
我想出了另一个使用 countrycode 包的解决方案:
library(countrycode)
countries <- data.frame(countryname_dict)
countries$continent <- countrycode(sourcevar = countries[["country.name.en"]],
origin = "country.name.en",
destination = "continent")
africa <- countries[ which(countries$continent=='Africa'), ]
library(stringr)
pat <- paste0("\\b", paste(africa$country.name.en , collapse="\\b|\\b"), "\\b")
df$country_list <- str_extract_all(df$country, regex(pat, ignore_case = TRUE))
解决方案
你可以这样做:
library(stringi)
vec <- stri_trans_general(countrycode::codelist$country.name.en, id = "Latin-ASCII")
stri_extract_all(df$country,regex = sprintf(r"(\b(%s)\b)",stri_c(vec,collapse = "|")))
[[1]]
[1] "Cote d'Ivoire"
[[2]]
[1] "South Africa" "United Kingdom"
[[3]]
[1] "Gambia" "Bangladesh" "Netherlands"
推荐阅读
- c - 主要发生之前的段故障
- angular - Angular - 您可以在没有初始值的情况下在 FormControl 上使用验证器吗?
- list - numpy 与 cython,在大型数据集迭代上更快吗?
- r - 为什么 as.numeric() 删除所有小数?
- android - 应用程序 A 启动应用程序 B 然后应用程序 A 关闭离开应用程序 B open.in Android ..如何实现?
- c++ - 使用 g++ 编译服务 DLL 以在 SvcHost.exe 中使用
- javascript - 如何使用 postinstall 编辑 package.json
- notepad++ - 当前工作目录中的自动完成文件名 Notepad++ 项目
- sql - 获取子字符串的聪明方法
- swift - 在 NSDictionary 中包装 Dictionary 以比较相等性(当值是 Any 时?)是一种安全模式吗?