【问题标题】:Exchange Rate for specific date and currency on a data frame数据框上特定日期和货币的汇率
【发布时间】:2021-09-12 14:47:36
【问题描述】:

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

这是我目前的代码:

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. Observation: 0.133754 而不是 0.1338419

【问题讨论】:

    标签: r currency-exchange-rates


    【解决方案1】:

    解决方案:

    #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
    

    【讨论】:

      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      相关资源
      最近更新 更多