-1

I have a data frame with a large number of rows. There's a date column and USD column.

Date          USD
20/02/2021    1000
16/01/2021    500

I want to create a new column with the GBP value of the USD amounts for the given dates. Is this possible? Maybe there's a function for this already?

Phil
  • 7,287
  • 3
  • 36
  • 66
Steve
  • 625
  • 2
  • 5
  • 17
  • Maybe the Quandl package? https://stackoverflow.com/questions/34454350/trick-to-getting-commodities-price-history-in-quantmod-r – Phil Feb 28 '21 at 17:07

1 Answers1

1

Try getFX in package quantmod. But you must coerce your date column to an object of class "Date".

library(quantmod)

exchange <- function(Date, amount, from, to){
  data.env <- new.env()
  getFX(
    Currencies = paste(from, to, sep = "/"),
    from = Date,
    to = Date,
    env = data.env
  )
  amount * data.env[[paste0(from, to)]]
}

currencies$Date <- as.Date(currencies$Date, "%d/%m/%Y")

GBP <- mapply(
  exchange, 
  currencies$Date, 
  currencies$USD, 
  MoreArgs = list(from = "USD", to = "GBP")
)

GBP
#[1] 713.71 367.95

currencies$GBP <- GBP

Data

currencies <- read.table(text = "
Date          USD
20/02/2021    1000
16/01/2021    500
", header = TRUE)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66