[R] A question regarding R scoping

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 7 01:10:54 CEST 2009


Steve and others have already directly answered your question
but to add to that note that the
way this would normally be done in R is to avoid the need
for references and environment handling in the first place
and just have f1 pass i back and have f2 assign f1's output to i.

f1 <- function(i) 1
f2 <- function(n) { i <- length(n); i <- f1(i); print(i) }
f2(1:10)

On Thu, Aug 6, 2009 at 4:11 PM, Ivo Shterev<idc318 at yahoo.com> 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).
>
> ivo
>
>
> --- 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, 3:07 AM
>> Hi,
>>
>> On Aug 5, 2009, at 5:55 PM, Ivo Shterev wrote:
>>
>> > I have a question related to scoping. Suppose we have
>> 2 functions:
>> >
>> > f1 = function(i){i = 1}
>> >
>> > f2 = function(n){
>> > i = length(n)
>> > f1(i)
>> > }
>> >
>> > In other words, I would like i=1 regardless of n. Is
>> this possible without having f1 in the body of f2? Thanks in
>> advance!
>>
>> Uhm ... what? You want i = 1 where, exactly? You want to
>> call to f1(i) to set i to 1 in f2?
>>
>> Sorry, I don't really follow. Can you be a bit more
>> explicit?
>>
>> -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
>>
>>
>
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list