I have a data set something like this:
value <- data.frame(Country = c('AUS', 'AUT', 'GBR'), amount = c(200, 150, 300))
every amount is given in the respectives country currency. So 200 in Aus. Dollar, 150 in Euro and 300 in Pound. What I want at the end is every number converted to the same currency, let's say Euro.
I already found something like library(quantmod)
but this only helps with conversion. So I would need to get the currency first only from the country code.
Any Ideas?
We can use the countrycode
package to convert ISO3 country codes into the relevant ISO4217 currency codes, then use priceR
to use that to convert each currency to a single one, Euros in this example.
Let's first get the currency code.
library(countrycode)
library(priceR)
value$currency_code <- countrycode(value$Country, "iso3c", "iso4217c")
value
#> Country amount currency_code
#> 1 AUS 200 AUD
#> 2 AUT 150 EUR
#> 3 GBR 300 GBP
We can then get all the latest Euro exchange rates.
e_df <- exchange_rate_latest("EUR")
#> Daily EUR exchange rate as at end of day 2022-01-18 GMT
head(e_df)
#> currency one_eur_is_equivalent_to
#> 1 AED 4.184241
#> 2 AFN 119.337926
#> 3 ALL 122.074346
#> 4 AMD 547.591037
#> 5 ANG 2.052008
#> 6 AOA 611.091441
Last, let's bring that the exchange into our data frame and calculate the amounts in Euros.
value$exchange_euro <- e_df$one_eur_is_equivalent_to[match(value$currency_code, e_df$currency)]
value$amount_euro <- value$amount / value$exchange_euro
value
#> Country amount currency_code exchange_euro amount_euro
#> 1 AUS 200 AUD 1.584396 126.2311
#> 2 AUT 150 EUR 1.000000 150.0000
#> 3 GBR 300 GBP 0.836131 358.7955