[R] A question regarding R scoping

Ivo Shterev idc318 at yahoo.com
Fri Aug 7 00:02:35 CEST 2009


Hi,

Perhaps I have to rephrase a bit my question. If we have the following:

i = 10
f1 = function(i){
i <<- 1
}

after calling f1, the value of i becomes 1. Now, suppose that f1 is called in another function f2, and i is initialized in f2 as well, i.e:

f2 = function(n){
i = n
f1(i)
}

The intention is, after executing f2, i=1 (not i=n).




--- On Thu, 8/6/09, Steve Lianoglou <mailinglist.honeypot at gmail.com> wrote:

> From: Steve Lianoglou <mailinglist.honeypot at gmail.com>
> Subject: Re: [R] A question regarding R scoping
> To: "Ivo Shterev" <idc318 at yahoo.com>
> Cc: r-help at r-project.org
> Date: Thursday, August 6, 2009, 10:23 PM
> 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