[R] A question regarding R scoping

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Aug 6 22:23:34 CEST 2009


Howdy,

On Aug 6, 2009, at 4:11 PM, Ivo Shterev wrote:

> Hi,
>
> The intention is that after executing f2, the value of i to become 1.
>
> f1 = function(i){i = 1}
>
> f2 = function(n){  i = length(n)
> f1(i)
> print(i)}
>
> i.e. f2 should print 1, not length(n).

Yeah, you can using parent.frame()'s and such:

f1 <- function(i) assign('i', 10, envir=parent.frame())
f2 <- function(n) {
   i <- length(n)
   f1(i)
   print(i)
}

R> f2(1:20)
[1] 10

Honestly, this just smells like a *really* bad idea, though ... just  
have f1() return a value that you use in f2.

-steve

--
Steve Lianoglou
Graduate Student: Computational Systems Biology
   |  Memorial Sloan-Kettering Cancer Center
   |  Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact




More information about the R-help mailing list