Reputation: 1932
I created this function:
nDone<- function (under,strike,ttoe,vol,rf,dy) {
return(pnorm(((log(under/strike) + (rf-dy+(vol^2)/2)*ttoe)/(vol*(ttoe^0.5)))))
}
nDone(90,100,3,0.17,0.05,0)
[1] 0.6174643
So far that's fine and works. Now I want the function to be applied to each row of a matrix.
b<- c(90,95,100,100,3,2,0.17,0.18,0.05,0.05,0,0)
dim(b) <- c(2,6)
Which gives:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 90 100 3 0.17 0.05 0
[2,] 95 100 2 0.18 0.05 0
So now I want to pass the elements in each row to the function. I've tried using apply:
apply(b,1,nDone)
And get the following error:
Error in under/strike : 'strike' is missing
I've also tried:
lapply(b,nDone)
I get the following error:
Error in under/strike : 'strike' is missing
What I want is multiple results of the function. What am I doing wrong here?
Upvotes: 0
Views: 2636
Reputation: 2481
It is worth mentioning that, if you wanted to bind the results of the functions to the original matrix, you could use mdply
from plyr
> library(plyr)
> mdply(b, nDone)
X1 X2 X3 X4 X5 X6 V1
1 90 100 3 0.17 0.05 0 0.6174643
2 95 100 2 0.18 0.05 0 0.6249916
Upvotes: 3
Reputation: 89057
This should work:
apply(b, 1, function(x)do.call(nDone, as.list(x)))
What was wrong with your version is that through apply(), your nDone() function was getting the whole row as a single argument, i.e., a vector passed under "strike" and nothing for the other arguments. The solution is to use do.call().
Upvotes: 6