Adding continent/region column to data frame using countrycode package

917 views Asked by At

I need to add a column to my dataframe which which gives the region/continent based on the data provided in column "Country.region" using the countrycode package. I do need to maintain the X1, X2, x3, x4, x5, x6 columns.

My data (tibble [189 × 37] (S3: tbl_df/tbl/data.frame)) look like this:

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
1

There are 1 answers

3
CJ Yetman On
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