Translating Country Names from Spanish to English with translateR

Viewed 824

I have a data set with country names and exports, but the country names are in Spanish. I want to use countrycode to get the proper codes to map it, however countrycode only converts from English/German to other languages (not the other way around). I tried using translateR to change the Spanish names to English, but the new column outputs the exact same thing as the original.

I don't think it is my API because I was getting a different error for that originally, but then I restarted R and it went away. Is it something in the code?

#read in file
data <- read.csv("...", header = TRUE)
data$char <- as.character(data$pais_descripcion)

#translate
library(translateR)

google.dataset.out <- translate(dataset = data,
content.field = 'char',
google.api.key = 'key',
source.lang = 'es',
target.lang = 'en')

Dataset with countries(pais_descripcion)

1 Answers

countrycode does have Spanish country names built-in, but it's not accessible as an origin code by default. You can work around that by creating and using a custom dictionary as in the example below. The disadvantage is that it won't match with regex, so the names have to match exactly (including case-sensitivity). If you're able and willing to create a set of regexes for Spanish country names, we'd be very happy and grateful to integrate them into countrycode as a default accessible origin code (submission is possible here https://github.com/vincentarelbundock/countrycode).

library(countrycode)

custom_dict <- data.frame(spanish = countrycode::codelist$cldr.name.es,
                          english = countrycode::codelist$cldr.name.en,
                          stringsAsFactors = FALSE)

countries <- c("España", "Alemania")

countrycode(countries, "spanish", "english", custom_dict = custom_dict)
# [1] "Spain"   "Germany"

It matches on 92% of the country names in the data you're using, which is at least a good start. You could add entries for the country names it doesn't match to the custom dictionary to match all of them.

library(countrycode)

url <- "https://catalogo.datos.gba.gob.ar/dataset/46b85203-17fe-42bd-b13f-1d3e150c06cd/resource/3eb20f55-7dc0-4671-a039-cf2e4b71c3db/download/expo_2016_2017.xlsx-expo.csv"
data <- read.csv(url, stringsAsFactors = FALSE)

custom_dict <- data.frame(spanish = countrycode::codelist$cldr.name.es,
                          english = countrycode::codelist$cldr.name.en,
                          stringsAsFactors = FALSE)

results <- countrycode(data$pais_descripcion, "spanish", "english", custom_dict = custom_dict)

sum(is.na(results))
# [1] 3902

sum(!is.na(results))
# [1] 45060
Related