Skip to content
Back to formatted view

Raw Message

Message-ID: <558889.47660.qm@web36908.mail.mud.yahoo.com>
Date: 2009-08-06T22:02:35Z
From: Ivo Shterev
Subject: A question regarding R scoping
In-Reply-To: <F5D09EE8-3C0A-4838-A530-EDC901FD03BF@gmail.com>

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
> 
>