R applies the function to the rows of the data frame, using values ​​as arguments

I have df TRX with Date and Curreny pairs

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

I have a second df CURRENCIES for 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 daily 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 TRX line so that for each line it uses the first and second elements as arguments, so I get teh ExchangeRate .

apply(x,1,fun()) does not work, since this requires a matrix with numbers. Theoretically, I would have to convert the data to indexes and then use apply.

Is there a better way?

+4
source share
3 answers

With mapply you can do something like:

 mapply(getDayRate, TRX$Date, TRX$Currency) 
+5
source

The selected conclusion is not so clear. your getDayRate function retrieves directly from the currencies table, the hard-coded table in it, the ExchangeRate date and currency, which still makes sense.

However, by running your function against the same table, it extracts values ​​from the same result as when you select this column ...

 > all.equal(mapply(getDayRate, currencies$Date, currencies$Currency), currencies$ExchangeRate, check.attributes=F) [1] TRUE 

I probably think that you really want to make several joins (with the second table you provided?) By linking another table with currencies data.frame using date and currency .

EDIT:

your editing now clarifies things. why don't you try this

 library(reshape2) melt(currencies) 
+1
source

This should do this in order to get apply to work:

 apply(your_df, 1, function(x) {getDayRate(x[1], x[2])}) 
0
source

Source: https://habr.com/ru/post/1488495/


All Articles