我正在编写一个需要默认参数才能工作的包函数,但其值必须取自函数的已处理(其他)参数。截至目前,我这样做:
myfunc <- function(x, y, n=NULL){
processed <- some_other_func(x,y)
x <- processed$x
y <- processed$y
if(is.null(n)){
n <- length(intersect(x,y))/3
}
# do stuff
}
但理想情况下,我想要一个默认表达式而不是NULL
,因为如果我的文档说默认值是length(intersect(x,y))/3
,它似乎不一致。
你知道我可以指定默认参数的方式更容易理解吗?
也许你可以解决这个问题吗?
default_function <- function(v1, v2)
{
return((v1 + v2)/2)
}
dummy_function <- function(x, y, n = default_function)
{
x = x
y = y
if(class(n) == "function") n = n(x,y) # if n is any kind of function do it
print(paste(x, y, n))
}
dummy_function(1, 2)
dummy_function(1, 2, 100)