假定我有一个外部函数,该函数具有一个数字参数和一个本身就是函数的参数(内部函数).如何将外部函数的数字参数的值作为内部函数的参数传递?考虑这个玩具示例:
Assume I have an outer function that has a numeric argument and an argument which is a function itself (inner function). How can I pass the value of the numeric argument of the outer function as an argument to the inner function? Consider this toy example:
innerfun <- function(M){ 1:M } outerfun <- function(x, fun){ x * fun } outerfun(x = 3, fun = innerfun(M = 3)) ## works outerfun(x = 3, fun = innerfun(M = x)) ## error because innerfun can't find 'x' outerfun(x = 3, fun = innerfun(M = get("x"))) ## doesn't work either...所以我想做的是在评估externalfun的参数时调用innerfun,使用对innerfun的调用中的这些externalfun参数.有什么想法或建议吗?
So what I want to do is to call innerfun at the moment the arguments of outerfun are evaluated, using those outerfun-arguments in the call to innerfun. Any ideas or suggestions?
推荐答案我会做这样的事情:
outerfun <- function(x, fun,...){ x * fun(x,...) } innerfun <- function(M){ seq_len(M) ## safer than 1:M } outerfun(x=3, innerfun) [1] 3 6 9请注意,如果内部函数具有多个参数,则它仍然有效:
Note that If inner function has more than one argument, it still works :
innerfun2 <- function(M,Z){ seq(M+Z) } outerfun(x=3, innerfun2,Z=3) [1] 3 6 9 12 15 18更多推荐
将函数参数传递给其他本身就是函数的参数
发布评论