数据框上特定日期和货币的汇率

Exchange Rate for specific date and currency on a data frame

我需要每次观察(每次观察都有不同的货币和日期戳)特定日期和货币的汇率。

到目前为止,这是我的代码:

library(priceR)
library(ggplot2)
library(tidyverse)
library(tibble)
library(dplyr)

#Data frame
df <- data.frame(
  currency = c("DKK", "USD", "DKK"),
  price = c(580.9, 539.75, 567.8),
  Date = c("2020-01-01", "2020-02-15", "2020-03-15")
)

#Function to pull conversions
avg_ex <- function(x){
  historical_exchange_rates(x, to = "EUR",start_date = "2020-01-01", end_date = "2020-03-15") %>%
    `colnames<-`(c('date','conv')) %>% summarise(mean(conv)) %>% as.numeric
}

#Apply across all needed
conversions = sapply(unique(df$currency),avg_ex) %>% data.frame() %>% rownames_to_column() %>%
  `colnames<-`(c('currency','conv'))

#Join and convert
df %>% left_join(conversions,by='currency') %>%
  mutate(price_euro = price*conv)

  currency  price       Date      conv price_euro
1      DKK 580.90 2020-01-01 0.1338419   77.74876
2      USD 539.75 2020-02-15 0.9047106  488.31752
3      DKK 567.80 2020-03-15 0.1338419   75.99543

输出几乎是我需要的。除了,转换率只是从“2020-01-01”到“2020-03-15”的平均值

例如我需要 1。观察:0.133754 而不是 0.1338419

解决方案:

#Data frame
df <- data.frame(
  currency = c("USD", "DKK", "USD", NA),
  price = c(10, 11, 12, 13),
  date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"))
)
head(df)

#Function to pull conversions
avg_ex <- function(x, y){
  if (is.na(x)) 0 
  else historical_exchange_rates(x, to = "EUR", start_date = y, end_date = y) %>%
    `colnames<-`(c('date','conv')) %>% summarise(conv) %>% as.numeric
}


#Apply across all needed
df$conv = mapply(avg_ex, df$currency, df$date) %>% data.frame() %>% rownames_to_column() %>%
  `colnames<-`(c('currency','conv'))
df