How to convert ISO-4217-Code to currency name in R

I have a large dataset with various currencies. As for visualisation purpose I would like to display the full name of the currencies and not the ISO-4217-Code (currency code).

Let me take the following excerpt of the data:

# dataframe
id = rep(1:8)
country = c("USA", "Canada", "UK", "Switzerland", "USA", "Sweden", "Switzerland", "Canada")
currency_code = c("USD", "CAD", "GBP", "CHF", "USD", "SEK", "CHF", "CAD")

df1 = data.frame(id, country, currency_code)

I could now with a left join manually assigning the currency name to the ISO-4217-Code which would work. But I'm looking personally for a more elegant way to do it than below shown:

country = c("USA", "Canada", "UK", "Switzerland", "Sweden")
currency_name = c("US Dollar", "Canadian Dollar", "Great Britain Pound", "Swiss franc", "Swedish krona")

df2 = data.frame(country, currency_name)

#left join
merge(df1, df2, by = "country", all.x = TRUE)

So my desired data would look like this

  country      id currency_code       currency_name
  Canada        2           CAD     Canadian Dollar
  Canada        8           CAD     Canadian Dollar
  Sweden        6           SEK       Swedish krona
  Switzerland   4           CHF         Swiss franc
  Switzerland   7           CHF         Swiss franc
  UK            3           GBP Great Britain Pound
  USA           1           USD           US Dollar
  USA           5           USD           US Dollar

With the countrycode package it is possible to assign country names to the country code (vice versa). Also it is possible to assign the currency code to a country, which is sadly not what my goal is.

I am aware that a left join would also give me a solution, but I would appreciate it if someone knows a better approach.

1 answer

  • answered 2021-05-03 17:58 akrun

    We can use the currency_list dataset from currencycode and join the 'currency_code' column with the input dataset 'df1'

    # remotes::install_github("KKulma/currencycode")
    currency_list %>%
       select(currency_code, currency_name) %>%
       filter(complete.cases(currency_code)) %>%


    #    currency_code   currency_name id     country
    #1           CAD Canadian Dollar  2      Canada
    #2           CAD Canadian Dollar  8      Canada
    #3           CHF     Swiss Franc  4 Switzerland
    #4           CHF     Swiss Franc  7 Switzerland
    #5           GBP  Pound Sterling  3          UK
    #6           SEK   Swedish Krona  6      Sweden
    #7           USD       US Dollar  1         USA
    #8           USD       US Dollar  5         USA