Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

r - How can I pass multiple arguments to a function as a single vector?

I created the following function with six args:

nDone <- function(under,strike,ttoe,vol,rf,dy) {
    pnorm(((log(under/strike)+ (rf-dy+(vol^2)/2)*ttoe)/(vol*(ttoe^0.5))))
}

nDone(90,100,3,0.17,0.05,0)
# Result: 
[1] 0.6174643

Now I create a vector with the same values in an object, and try to call the function using the vector, but get the following error:

d <- c(90,100,3,0.17,0.05,0)

nDone(d)

Error in under/strike : 'strike' is missing

What am I doing wrong and how to fix?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

 do.call(nDone, as.list(d))

Explanation of what's happening in your first attempt by @joran from the comments:

R is seeing you pass a single argument to nDone, namely the vector d, which is handed off to the first function argument, under. Since you haven't specified a default value for the others, they are missing and hence the error


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...