R 2.11.1中的范围界定和功能:出了什么问题? [英] Scoping and functions in R 2.11.1 : What's going wrong?

查看:104
本文介绍了R 2.11.1中的范围界定和功能:出了什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自一系列其他问题,都涉及基本相同的问题。出于某种奇怪的原因,在另一个函数中使用函数有时会失败,因为在第一个函数的本地环境中定义的变量在第二个函数中找不到。



伪代码中的经典模式:

  ff < -  function(x){
y < - some_value
some_function(y)
}
ff(x)




eval(expr,envir,enclos)错误:
找不到对象'y'

首先,我认为它与S4方法和范围在那里有关,但它也发生在其他功能上。我已经与R开发团队进行了一些交流,但他们所做的只是将我引导到bug报告网站(这不是最吸引人的,我不得不说)。我从来没有得到任何反馈。



随着问题的不断出现,我不知道是否有逻辑解释。在所有这些情况下,这是一个常见的错误,如果是这样,哪一个?或者它确实是一个错误?



其中一些问题:

$ b:b
PS:我知道R-devel列表,以防万一如果Dirk在他的回答中提到的话,那么你发布的代码实际上并没有问题。在问题中发布的链接中,似乎有一个共同的主题: some_function 包含以某种方式混淆环境的代码。使用 new.env 加上或隐式地使用数据参数,可能有一行,如

  y < -  eval(substitute(y),数据)

故事的寓意是双重的。首先,尽量避免明确地操纵环境,除非你确定你知道你在做什么。其次,如果一个函数有一个数据参数,然后把所有需要该函数的变量放在该数据框中。


This question comes from a range of other questions that all deal with essentially the same problem. For some strange reason, using a function within another function sometimes fails in the sense that variables defined within the local environment of the first function are not found back in the second function.

The classical pattern in pseudo-code :

ff <- function(x){
    y <- some_value
    some_function(y)
}
ff(x)

Error in eval(expr, envir, enclos) : object 'y' not found

First I thought it had something to do with S4 methods and the scoping in there, but it also happens with other functions. I've had some interaction with the R development team, but all they did was direct me to the bug report site (which is not the most inviting one, I have to say). I never got any feedback.

As the problem keeps arising, I wonder if there is a logic explanation for it. Is it a common mistake made in all these cases, and if so, which one? Or is it really a bug?

Some of those questions :

PS : I know the R-devel list, in case you wondered...

解决方案

As Dirk mentioned in his answer, there isn't actually a problem with the code that you posted. In the links you posted in the question, there seems to be a common theme: some_function contains code that messes about with environments in some way. This messing is either explicit, using new.env and with or implicitly, using a data argument, that probably has a line like

y <- eval(substitute(y), data)

The moral of the story is twofold. Firstly, try to avoid explicitly manipulating environments, unless you are really sure that you know what you are doing. And secondly, if a function has a data argument then put all the variables that you need the function to use inside that data frame.

这篇关于R 2.11.1中的范围界定和功能:出了什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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