我有一个包含国家和其他区域名称的字符串。我只对国家名称感兴趣,最好是添加几个列,每个列都包含字符串中列出的国家名称。下面是数据结构设置的示例性代码:
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)我想知道是否可以使用分隔符,但定义异常(如“联合王国”)。这显然需要一些手工工作,但对我来说似乎是最可行的解决方案。有人知道如何定义这样的例外吗?当然,我也对任何其他解决办法持开放态度,并对此表示感谢。
更新:
我想出了另一种使用国家代码包的解决方案:
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))发布于 2020-11-20 22:28:13
你可以这样做:
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"https://stackoverflow.com/questions/64937308
复制相似问题