将函数参数传递给其他本身就是函数的参数

编程入门 行业动态 更新时间:2024-10-22 23:42:42
本文介绍了将函数参数传递给其他本身就是函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假定我有一个外部函数,该函数具有一个数字参数和一个本身就是函数的参数(内部函数).如何将外部函数的数字参数的值作为内部函数的参数传递?考虑这个玩具示例:

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

更多推荐

将函数参数传递给其他本身就是函数的参数

本文发布于:2023-11-24 09:07:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!