[R] lexical scope

John Fox jfox at mcmaster.ca
Tue Apr 22 16:32:35 CEST 2003


Dear Robin,


>On Tue, Apr 22, 2003 at 04:07:39PM +1200, Robin Hankin wrote:
>Hi everyone
>
>another documented feature that was a bit unexpected for me:
>
>  R> x <- 19
>  R> f <- function(t){t+x}
>  R> f(100)
>  [1] 119
>
>  --as expected: x is visible from within f()
>..but...
>
>
>  R> g <- function(a){x <- 1e99 ; return(f(a))}
>  R> g(4)
>  [1] 23
>
>  --the "x" that is visible from within g() is just 19, which is not the
>    one I expected it to find.


A couple of people have pointed out that the source of the difficulty here 
is lexical scoping. One can sometimes take advantage of lexical scoping by 
defining a local function. For your illustration, for example,

 > x <- 19
 > g <- function(a){
+     f <- function(t){t + x}
+     x <- 1e99
+     f(a)
+     }
 > g(4)
[1] 1e+99
 >

Whether or not this solves your problem depends upon whether it's 
reasonable to make f local to g.

John


-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox



More information about the R-help mailing list