文字列から地方区分を抽出し、Rで国名に変換します

Aug 22 2020

Rで国名ベクトルに変換したい州名/地方区分名のみを含む一連の文字列があります。countrycodeパッケージを使用して国名を抽出するのは比較的簡単ですが、州名をに変換する方法がわかりません。そのパッケージを使用している国。

例えば:

provinces <- c("The governor of Florida", "The Premier of Ontario", "Jalisco has a province-wide policy")

provincesベクトルをのようなベクトルに変換する方法を望んでいc("United States of America", "Canada", "Mexico")ます。

回答

2 firebird17139 Aug 22 2020 at 10:00

上記のコメントから、でカスタム辞書を使用できることに気付きましたcountrycode。これにより、地方のデータを組み込むことができます。

編集:

最後のものが完全に機能しなかったので、これは完全に再現可能な例です:

require(countrycode)
require(choroplethrAdmin1)

# example data
provinces <- c("The governor of Florida", "Tim Stevenson leads Oxfordshire", "Gobierno del Estado de Hidalgo")

# remove punctuation
provinces <- gsub("[[:punct:]\n]", "", provinces)

# load administrative division dictionary
data(admin1.regions)

# remove duplicate region names (countrycode function only accepts unique names)
admin1.regions <- admin1.regions[!duplicated(admin1.regions$region),]

# convert provinces to country
provinces_to_country <- countrycode(provinces, "region", "country", custom_dict = admin1.regions, origin_regex = TRUE) 

古い、再現できない例:

require(countrycode)
require(choroplethrAdmin1)

# example data
provinces <- c("The governor of Florida", "The Premier of Ontario", "Jalisco has a province-wide policy")

# remove punctuation
provinces <- gsub("[[:punct:]\n]", "", provinces)

# load administrative division dictionary
data(admin1.regions)

# remove duplicate region names (countrycode function only accepts unique names)
admin1.regions <- admin1.regions[!duplicated(admin1.regions$region),]

# convert provinces to country
provinces_to_country <- countrycode(provinces, "region", "country", custom_dict = admin1.regions, origin_regex = TRUE)