samedi 4 septembre 2021

Using if functions to perform calculations across two tables - Rstudio

i'm trying to use an if function (unless there's a better way!) to convert EUR and USD amounts into GBP. I have two tables, one is of currency conversation rates, and one is of people's holiday spending.

Holiday Spending

Date<- c('01/01/2021', '02/01/2021','01/01/2021', '02/01/2021','01/01/2021', '02/01/2021','01/01/2021', '02/01/2021' )
Person <- c('Person A', 'Person B', 'Person C', 'Person A', 'Person B', 'Person C', 'Person A', 'Person B')
Amount <- c('100',  '150',  '200',  '250',  '300',  '350',  '400',  '450')
Currency <- c('GBP',    'EUR',  'USD',  'GBP',  'GBP',  'GBP',  'EUR',  'USD')

DF <- data.frame(Date, Person, Currency, Amount) 

Conversation Rates

Date<- c('01/01/2021', '01/01/2021','02/01/2021', '02/01/2021','03/01/2021', '03/01/2021','04/01/2021', '04/01/2021' )
Country <- c('EUR', 'USD',  'EUR',  'USD',  'EUR',  'USD',  'EUR',  'USD')
Rate <- c('2',  '4',    '6',    '8',    '10',   '12',   '14',   '16')


XR <- data.frame(Date, Country, Rate)

What I'm looking to do is search the currency list of the holiday spending, and if the Currency column says anything not GBP, then to find the currency conversation rate of that day and re calculate the Amount column to that.

So for example, person B spend 150 Euros on the 02/10/2021, the conversation rate that day was 6 so then that 150 should be recalculated to 900, I don't need the currency column to change as it gets filtered out anyway when I rejig the tables later in the process.

I can do it in excel with vlookups and an if function, but i'm struggling to translate this to R. In Excel I have the EU and USD exchange rates on different tabs but in R it's one big table. I could split it into small tables but still not sure how to get the if and sum to work in an R format.

Excel function

=IF(D2="EUR",SUM(E2 * VLOOKUP(A2,EU!A:D,3,FALSE)),IF(D2="USD",SUM(E2* VLOOKUP(A2,USD!A:D,3,FALSE)),Spending!E2))

grateful for your advice.

Aucun commentaire:

Enregistrer un commentaire