Search code examples
rpanel-datacountry-codes

How to use the codelist_panel of the countrycode package in R


I'm trying to use the panel codelist from the countrycode package in R, but have no idea how to include the years.

I have a dataset with countrynames and years, I would like to add the corresponding cow-code as a new variable or replace the country names. I just don't know how to do that.

My data looks a bit like this:

country <- c("Australia", "Australia", "Canada", "Belgium")
year <- c(1995, 2000, 1880, 1885)
a <- c( 5.55, 4.5, 6.75, 8.3)

data<- data.frame(country, year, a)

I think this is the standard approach:

data$country2 <- countrycode(data$country, "country.name", "cown", warn = TRUE)

I get a variable "country2" with the corresponding codes, but not the correct codes for that time period. Accodring to the package manual I should be able to tuse the codelist_panel, but I just dont know how and there are no useful examples. Every hint is highly appreciated! Thanks!


Solution

  • You need to merge your data and codelist_panel.

    Input data - I changed the column name of the country column so we can specify it together with the year column in the by argument below.

    dat <- data.frame(country.name.en = country, year, a)
    

    Result

    library(countrycode)
    merge(dat,
          codelist_panel[, c("country.name.en", "year", "cown")],
          by = c('year', 'country.name.en'))
    #  year country.name.en    a cown
    #1 1880          Canada 6.75   NA
    #2 1885         Belgium 8.30  211
    #3 1995       Australia 5.55  900
    #4 2000       Australia 4.50  900