rcurrency-exchange-rates

R: Multiply values in one column to those in another if the dates coincide


I've been trying this for some days but I can't seem to find a way to do it. I have a two dataframes. One named "df1" with two variables: date, price

         date        price
        2019-12-21    140
        2019-10-25     91
        2019-10-24     91    
        2019-12-13     70

Another one, named "df2" with two variables: date, exchange rate

         date        exchange rate
        2019-12-21    1.1097
        2019-12-22    1.117
        2019-12-23    1.1075  
           ...         ...
        2019-12-13    1.108
           ...         ...
        2019-10-25    1.1074
        2019-10-24    1.1073


I want to multiply the exchange rates from df2 by the prices in df1 WHEN the dates coincide. And add that into a column in df1. So the result would be like this:

         date        price    priceEUR
1       2019-12-21    140      155.358
2       2019-10-25     91      100.7734
3       2019-10-24     91      100.7643
4       2019-12-13     70      77.56

Thank you very much.


Solution

  • One way is to:

    library(tidyverse)
    
    df3 <- inner_join(df1, df2)
    
    df3 <- df3 %>%
        mutate(priceEUR = price * rate)