0

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?

4
  • Um....this is exactly the same as your last question. Commented Feb 10, 2012 at 23:33
  • Hi Joran, I know it looks the same and I'm certainly not trying to waste anyone's time. In this question now I'm trying to pass each row of a matrix to a function. Again thanks for reviewing. Commented Feb 10, 2012 at 23:43
  • Yes. @joran's answer (actually a comment) to the previous question should work to answer this one as well. He left a little bit of room for struggle/interpretation on your part. I would suggest that you take a look at his comment, see if you can understand what to do with it, then (if you can't) come back and ask for clarification there ... Commented Feb 10, 2012 at 23:59
  • Another route you could go down would be something like this: nDone(b[,1],b[,2],b[,3],b[,4],b[,5],b[,6]), since nDone is already vectorized. Or convert the matrix to a list with each column being an element and use the solution from the previous question. Commented Feb 11, 2012 at 0:09

2 Answers 2

6

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().

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.