在R中的函数内部定义函数的好方法 [英] Good ways to define functions inside function in R

查看:64
本文介绍了在R中的函数内部定义函数的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,当要在另一个函数中使用一个/多个函数时,也许有两种方法.一个示例函数可以是:

In R, when want to use one/multiple functions inside another function, maybe there are two ways. An example function can be:

方法1:

make.power <- function(n) {
 pow <- function(x) {
 x^n
 }
 pow
}

方法2:

make.power <- function(n) {
     pow(n)
    }

pow <- function(x) {
     x^n
     }

在我看来(但我不确定),如果您有很多子函数供父函数使用,则第二种方法是一种更好的方法.

In my opinion (but I am not sure), the second method is a better way if you have lots of child functions for the parent one.

我的问题是:1)两种方式在功能上有什么不同?例如,函数将如何传递变量,或者子函数与父函数之间的关系等.

My questions are: 1) Are there any functional differences between the two ways? E.g., how the function will pass variables, or the relationship between the children and parent functions, etc..

2)哪个可能是R的首选(计算效率更高或结构上更清晰)?

2) which one might be a preferred one (maybe more computational efficient or structurally clear) for R?

推荐答案

如果您要询问所举的具体示例,那么这个问题对我来说似乎并不广泛.

If you are asking about the specific example you gave, this question does not seem too broad to me.

这里的主要区别是对 n 的评估.对于示例1 ,返回的函数本质上将具有硬编码的 n 值.

The main difference here is the evaluation of n. For example 1, the function that gets returned will essentially have a hard-coded n value.

> n = 100
> f1 = make.power(2)
> f1(2)
[1] 4
> n = 1
> f1(2)
[1] 4

示例2 不会,而是依赖于 n 的全局定义.

Example 2 will not, instead it will rely on the global definition of n.

> n = 1
> make.power2(2)
[1] 2
> n = 100
> make.power2(2)
[1] 1.267651e+30

随着功能变得越来越复杂,范围界定问题也会越来越复杂.David Robinson在评论中提供的链接是一个很好的资源.

As functions get more complex, so will the scoping issues. The link David Robinson provides in the comments is a great resource.

这篇关于在R中的函数内部定义函数的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆