从R中的国家名称获取世界地区名称

问题描述 投票:0回答:1

在我的数据中,我有一栏包含国家名称。我想创建一个新变量,根据我拥有的Excel工作表列出每个国家/地区所在的区域,该表格按区域标记了每个国家/地区。

我不想使用国家/地区代码包,因为它没有足够明确的区域(即,将荷兰标记为欧洲,而不是北欧)。有没有办法让R检查单元格并将该单元格的内容与另一个数据集匹配?

r region country
1个回答
0
投票

将电子表格导入R。(使用RExcel,或导出为CSV并使用基本函数导入。)假设您的电子表格有两列,分别为CountryRegion,如下所示:

regions <- data.frame(Country = c("Greece", "Netherlands"), 
                      Region = c("Southern Europe", "Northern Europe"),
                      stringsAsFactors = FALSE)
regions
#>       Country          Region
#> 1      Greece Southern Europe
#> 2 Netherlands Northern Europe

现在从数据框中创建一个命名向量:

named <- regions$Region
names(named) <- regions$Country
named
#>            Greece       Netherlands 
#> "Southern Europe" "Northern Europe"

现在您可以索引命名的向量,以将国家/地区名称转换为任何其他向量中的区域。

other <- c("Netherlands", "Greece", "Greece")
named[other]
#>       Netherlands            Greece            Greece 
#> "Northern Europe" "Southern Europe" "Southern Europe"

如果您有任何缺少的国家(或不同的拼写),您将获得该区域的NA,例如

other2 <- c("Greece", "France")
named[other2]
#>            Greece              <NA> 
#> "Southern Europe"                NA
© www.soinside.com 2019 - 2024. All rights reserved.