R apply function to rows of data frame using values as arguments
Solution 1
With mapply
you could do something like:
mapply(getDayRate, TRX$Date, TRX$Currency)
Solution 2
The output you want is not so clear. your function getDayRate
retrieves directly, from the currencies
table hard-coded into it, the ExchangeRate chosen date and currency which makes sense so far.
However, running your function against the same table it retrieves the values from we give the same result of just selecting that column...
> all.equal(mapply(getDayRate, currencies$Date, currencies$Currency), currencies$ExchangeRate, check.attributes=F)
[1] TRUE
Probably (I think) you actually want to do some joins (with the second table you provided?) linking another table to the currencies
data.frame by date
and currency
.
EDIT:
your edit now clarifies things. why don't you try also this
library(reshape2)
melt(currencies)
Related videos on Youtube
user670186
Updated on September 16, 2022Comments
-
user670186 over 1 year
I have a df
TRX
with pairs of Date and CurrenyDate 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 ofTRX
so that for each row it uses the first and second element as arguments so I get tehExchangeRate
.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?
-
dickoa almost 11 yearsCan you post the
getDayRate
function ? -
Thomas almost 11 yearsTake a look at
mapply
. -
dickoa almost 11 years+1 I think
mapply
is the way to go
-
-
user670186 almost 11 yearsthat should work, but I get a an error: Error in as.matrix.data.frame(X) : dims [product 5000] do not match the length of object [5009]
-
user670186 almost 11 yearsproblem is it seems apply converts the dataframe to a matrix. in that conversion the matrix is longer than my data frame and I have no idea why
-
Michele almost 11 yearstry with
adply
fromplyr
. the actual problem is the everything in this question seems meaningless to me... -
eddi almost 11 years@user670186 I'm guessing that's because your function doesn't return a single number; I agree with Michele, it's unclear what you're trying to do - what exactly is
ExchangeRate
supposed to be? why do you have several dates per currency in yourcurrencies
table?