我有两个数据集,baci_2002和country_codes。Baci_2002有1到3位数字的国家代码,我想将它们改为3个字母的国家代码。数据集country_codes是一个表,它具有不同国家/地区代码的不同转换,如下所示:

Baci_2002看起来像这样:

Baci_2002中的"I“和"j”列是具有1到3个数字代码的国家/地区,我想将这些代码转换为iso_3digit_alpha of country_codes的格式。因此,在country_codes中,列country_code和iso_3digit_alpha之间必须进行比较。
我知道有一个包的国家代码,这个孩子的操作,但它不适用于我的R版本。
发布于 2020-12-09 04:39:53
您希望执行包含两个数据集的join。假设您希望保持baci数据的完整性,并且只获得3个字母的alpha代码,我们将通过将一列数据(baci_2002中的i)中的值与另一列(country_codes中的country_code)中的值进行匹配来执行left_join()。
require(tidyverse)
newData <- left_join(baci_2002, country_codes, by=c('i'='country_code'))你会得到很多列,随便你喜欢哪一个。
发布于 2020-12-09 04:38:54
R pkg countrycode depends on R (>= 2.10) and has zero other dependencies的当前版本...我发现它不能与您使用的R版本一起工作,这是非常不可能的。你一定有一个非常罕见的设置。
如果您有一个用于数字国家代码的查找表,则可以在基数R中执行此操作,如下所示...
country_codes <- data.frame(
country_code = c(4, 12, 20, 36),
iso_3digit_alpha = c("AFG", "DZA", "AND", "AUS")
)
baci_2002 <- data.frame(
t = rep(2002, 12),
i = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4),
j = c(12, 12, 12, 12, 12, 20, 20, 36, 36, 36, 36, 36)
)
baci_2002$i_iso3c <-
country_codes$iso_3digit_alpha[match(baci_2002$i, country_codes$country_code)]
baci_2002$j_iso3c <-
country_codes$iso_3digit_alpha[match(baci_2002$j, country_codes$country_code)]
baci_2002
#> t i j i_iso3c j_iso3c
#> 1 2002 4 12 AFG DZA
#> 2 2002 4 12 AFG DZA
#> 3 2002 4 12 AFG DZA
#> 4 2002 4 12 AFG DZA
#> 5 2002 4 12 AFG DZA
#> 6 2002 4 20 AFG AND
#> 7 2002 4 20 AFG AND
#> 8 2002 4 36 AFG AUS
#> 9 2002 4 36 AFG AUS
#> 10 2002 4 36 AFG AUS
#> 11 2002 4 36 AFG AUS
#> 12 2002 4 36 AFG AUS如果你知道如何安装countrycode,你可以这样做...
country_codes <- data.frame(
country_code = c(4, 12, 20, 36),
iso_3digit_alpha = c("AFG", "DZA", "AND", "AUS")
)
baci_2002 <- data.frame(
t = rep(2002, 12),
i = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4),
j = c(12, 12, 12, 12, 12, 20, 20, 36, 36, 36, 36, 36)
)
library(countrycode)
baci_2002$i_iso3c <- countrycode(baci_2002$i, "iso3n", "iso3c")
baci_2002$j_iso3c <- countrycode(baci_2002$j, "iso3n", "iso3c")
baci_2002
#> t i j i_iso3c j_iso3c
#> 1 2002 4 12 AFG DZA
#> 2 2002 4 12 AFG DZA
#> 3 2002 4 12 AFG DZA
#> 4 2002 4 12 AFG DZA
#> 5 2002 4 12 AFG DZA
#> 6 2002 4 20 AFG AND
#> 7 2002 4 20 AFG AND
#> 8 2002 4 36 AFG AUS
#> 9 2002 4 36 AFG AUS
#> 10 2002 4 36 AFG AUS
#> 11 2002 4 36 AFG AUS
#> 12 2002 4 36 AFG AUS仅供参考:由于很明显您使用的是CEPII的BACI数据,BACI数据中的3位国家代码被称为"ISO 3位数字代码“,但它们实际上是ISO 3166-1数字的自定义超集,即它们包括大约15个代码/数字,这些代码/数字不是官方ISO 3166-1数字国家代码系统的一部分。
https://stackoverflow.com/questions/65205827
复制相似问题