我用六个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
现在我在对象中创建一个具有相同值的向量,并尝试使用向量调用该函数,但得到以下错误:
d <- c(90,100,3,0.17,0.05,0)
nDone(d)
Error in under/strike : 'strike' is missing
我做错了什么以及如何解决?
答案 0 :(得分:32)
试试这个
do.call(nDone, as.list(d))
@joran从评论中首次尝试时发生的事情的说明:
R看到你将一个参数传递给nDone
,即向量d
,它被传递给第一个函数参数under
。由于您没有为其他人指定默认值,因此缺少这些值,因此错误
答案 1 :(得分:1)
也许值得补充:
如果您的函数可以接受长度大于 1 的向量参数并生成相同长度的输出,那么 do.call
也可以处理,您将需要 list()
:
x <- c("a", "b", "c")
y <- c(1, 2, 3)
> do.call(paste0,c(list(x),list(y)))
[1] "a1" "b2" "c3"
注意这不会失败或警告长度不等的向量:
x <- c("a", "b")
> do.call(paste0,c(list(x),list(y)))
[1] "a1" "b2" "a3"
当然 paste0(x,y)
也可以在这里工作,但我正在使用它,例如对于rgb()
:
# whichever complex functions to generate vector of floats:
x <- seq(1,6) %>% exp()
# rescale for rgb
x <- scales::rescale(x)
# make a list of vectors
# note that as.list() would not give the desired output here
x <- rep(list(x),3)
# call
> do.call(rgb, x)
[1] "#000000" "#030303" "#0B0B0B" "#212121" "#5D5D5D" "#FFFFFF"
或整洁的一行:
> seq(1,6) %>% exp() %>% scales::rescale() %>% list() %>% rep(3) %>% do.call(rgb,.)
[1] "#000000" "#030303" "#0B0B0B" "#212121" "#5D5D5D" "#FFFFFF"