Search code examples
rfunctioncurrency

Function to convert from one currency to another currency in R


Given the following, from 1 USD to

  • euro
  • peso
  • franc
  • Australian dollar
  • New Zealand dollar
  • Canadian dollar

How would I write a function to convert from one currency to another?

The function should work like this - amount is numeric, from and to are character strings:

currency(amount = 1, from = 'usd', to = 'euro')
## [1] 8.7

The only thing I can think if is to write numerous if statements, but that seems way too tedious for all these possibly currency conversions/combinations.

I'm also thinking of creating a named vector in my function like so: c('euro' = 0.93, 'peso' = 24.71, 'franc' = 0.98, ...) and so on to show the conversion rates from 1 USD to these currencies. But still not sure how to write a function that accounts for all these currency conversions (USD, euro, peso, franc, Austrian dollar, New Zealand dollar, Canadian dollar).


Solution

  • Here is a function, it does suffer from slight rounding error but just needs numbers with greater resolution to reduce that error - my values come from google searches of 10000 USD in each currency. You could also look at packages that scrape values from the web (rvest?) if you want to keep values updated automatically.

    currencyCon <- function(x, from = "USD", to = "EUR"){
      # assign values: 1 usd in each currency 
      values <- c(1.000000, 0.927985, 0.810100, 107.624500)
      # names attribute 
      names(values) <- c("USD", "EUR", "GBP", "YEN")
      # calculate (convert from into USD, and divide to)
      values[to] / (values[from] / x)
    }
    
    # Testing 
    currencyCon(1, "USD", "EUR")
    currencyCon(1, "EUR", "EUR")
    currencyCon(1, "GBP", "YEN")
    

    This returns

     > currencyCon(1, "USD", "EUR")
     EUR 
     0.927985
     > currencyCon(1, "EUR", "EUR")
     EUR 
     1 
     > currencyCon(1, "GBP", "YEN")
     YEN 
     132.8534