Search code examples
rconverterscountry-codes

How to convert country codes into country names


Here's my reproducible code:

library(tidyverse)
library(eurostat)
library(countrycode)

#Query eurostat data set
search <- search_eurostat("road", type = "table")

#Accessing "People killed in road accidents" data set.
df <- get_eurostat("tsdtr420")

#Create a data frame filtered on most recent data (2015)
accidents2015 <- df %>%
  filter(time == "2015-01-01") 

codes <- select(accidents2015, geo)

countrycode(sourcevar = codes, "iso2c", "country_name")

When the last line runs I get this error message:

the condition has length > 1 and only the first element will be usedError in countrycode(sourcevar = codes, "iso2c", "country_name") : sourcevar must be a character or numeric vector.


Solution

    1. pass a vector, not a data frame/tibble as the sourcevar

    2. use country.name, not country_name as the destination code

    3. in your specific case, you're better off using eurostat as the origin code

    for example...

    library(tidyverse)
    library(eurostat)
    library(countrycode)
    
    accidents2015 <- 
      get_eurostat("tsdtr420") %>%
      filter(time == "2015-01-01")
    
    countrycode(sourcevar = accidents2015$geo, "eurostat", "country.name")