Scoping and functions in R 2.11.1 : What's going wrong?

て烟熏妆下的殇ゞ 提交于 2019-11-28 23:27:53

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 has both lexical and dynamic scope. Lexical scope works automatically, but dynamic scope must be implemented manually, and requires careful book-keeping. Only functions used interactively for data analysis need dynamic scope, so most authors (like me!) don't learn how to do it correctly.

See also: the standard non-standard evaluation rules.

There are undoubtedly bugs in R, but a lot of the issues that people have been having are quite often errors in the implementation of some_function, not R itself. R has scoping rules ( see http://cran.r-project.org/doc/manuals/R-intro.html#Scope) which when combined with lazy evaluation of function arguments and the ability to eval arguments in other scopes are extremely powerful but which also often lead to subtle errors.

Well there is no problem in what you posted:

/tmp$ cat joris.r 
#!/usr/bin/r -t

some_function <- function(y) y^2

ff <- function(x){
    y <- 4
    some_function(y)  # so we expect 16
}
print(ff(3))          # 3 is ignored
$ ./joris.r 
[1] 16
/tmp$

Could you restate and postan actual bug or misfeature?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!