【问题标题】:Adding continent/region column to data frame using countrycode package使用国家代码包将大陆/地区列添加到数据框
【发布时间】:2021-02-02 14:37:25
【问题描述】:

我需要在我的数据框中添加一个列,该列使用 countrycode 包根据“Country.region”列中提供的数据给出区域/大陆。我确实需要维护 X1、X2、x3、x4、x5、x6 列。

我的数据(tibble [189 × 37] (S3: tbl_df/tbl/data.frame))如下所示:

data <-
  read.table(header = TRUE, text = "
Country.Region         X1      X2        X3      X4       X5      X6
Malawi        0       0        0        0        0       0
Algeria        0       0        0        0        0       3
China      151     725     1159     1322     1345    1350
Mauritania        0       0        0        0        0       0
Guinea        0       0        0        0        0       0
")

data
#>   Country.Region  X1  X2   X3   X4   X5   X6
#> 1         Malawi   0   0    0    0    0    0
#> 2        Algeria   0   0    0    0    0    3
#> 3          China 151 725 1159 1322 1345 1350
#> 4     Mauritania   0   0    0    0    0    0
#> 5         Guinea   0   0    0    0    0    0

【问题讨论】:

    标签: r dplyr country-codes


    【解决方案1】:
    library(dplyr)
    library(countrycode)
    
    data <-
      read.table(header = TRUE, text = "
    Country.Region         X1      X2        X3      X4       X5      X6
    Malawi        0       0        0        0        0       0
    Algeria        0       0        0        0        0       3
    China      151     725     1159     1322     1345    1350
    Mauritania        0       0        0        0        0       0
    Guinea        0       0        0        0        0       0
    ")
    
    data %>% 
      mutate(region = countrycode(sourcevar = Country.Region, 
                                  origin = "country.name",
                                  destination = "region"))
    #>   Country.Region  X1  X2   X3   X4   X5   X6                     region
    #> 1         Malawi   0   0    0    0    0    0         Sub-Saharan Africa
    #> 2        Algeria   0   0    0    0    0    3 Middle East & North Africa
    #> 3          China 151 725 1159 1322 1345 1350        East Asia & Pacific
    #> 4     Mauritania   0   0    0    0    0    0         Sub-Saharan Africa
    #> 5         Guinea   0   0    0    0    0    0         Sub-Saharan Africa
    

    【讨论】:

    • 非常感谢!这非常有用并且有效!有趣的是,我不需要具体说明“sourcevar”参数。您能否详细说明为什么我不必这样做?
    • sourcevar = Country.Region
    • 更新答案以明确命名sourcevar 参数以避免混淆
    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多