Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R apply function to rows of data frame using values as arguments

Tags:

r

apply

I have a df TRX with pairs of Date and Curreny

Date            Currency      ExchangeRate
2012-08-13      EUR           ?
2012-08-13      CHF           ?
2012-08-13      CZK           ?

I have a second df CURRENCIES for the currency conversion rates with EUR base.

Date            EUR    CHF       CZK
2012-08-13      1      1.24      25.73
2012-08-13      1      1.23      25.92
2012-08-13      1      1.22      24.00

Now I want to translate the day rates. I wrote a function for this liske getDayRate(date,currency).

getDayRate <- function(date, currency) {
currencies[which(as.character(currencies[,c("Date")]) == date),c(currency)]
}

getDayRate("2013-06-20","EUR")

Now I want to apply getDayRate(date,currency) to each row of TRX so that for each row it uses the first and second element as arguments so I get teh ExchangeRate.

apply(x,1,fun()) does not work as it requires a matrix with numbers. In theory i would have to convert the dataframes to the indices and then use apply.

Is there a better way?

like image 338
user670186 Avatar asked Mar 23 '23 09:03

user670186


1 Answers

With mapply you could do something like:

mapply(getDayRate, TRX$Date, TRX$Currency)
like image 107
Thomas Avatar answered Apr 06 '23 01:04

Thomas