[R] understanding the FUNCTION function

William Dunlap wdunlap at tibco.com
Thu Apr 26 16:49:35 CEST 2012


> Did you read ?'<<-'  as
> Peter suggested?

Better yet, do not read ?'<<-' and do not use <<-.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Ista Zahn
> Sent: Thursday, April 26, 2012 6:44 AM
> To: michaelyb
> Cc: r-help at r-project.org
> Subject: Re: [R] understanding the FUNCTION function
> 
> On Thu, Apr 26, 2012 at 8:56 AM, michaelyb <cel81009759 at gmail.com> wrote:
> > Peter, your solution is actually very interesting. I have never seen or heard
> > of before. I will look into it.
> >
> > Meanwhile, look at this example instead:
> > fac<-function(x){a<-1
> >                 for(i in 1:x){
> >                 a<-a*i
> >                 print(a)}}
> > The result is :
> >> fac(5)
> > [1] 1
> > [1] 2
> > [1] 6
> > [1] 24
> > [1] 120
> >
> > However, when I try your way:
> > fac<-function(x){a<-1
> >                 for(i in 1:x){
> >                 a<<-a*i
> >                 print(a)}}
> >
> > I get:
> >> fac(5)
> > [1] 1
> > [1] 1
> > [1] 1
> > [1] 1
> > [1] 1
> >
> > Why isn't it overriding "a", and giving me 120?
> 
> Because you are assigning a in the global environment and then
> printing a from the function environment. Did you read ?'<<-'  as
> Peter suggested?
> 
> Best,
> Ista
> 
> > PS: I am aware that I could use the FACTORIAL function, but I used this
> > example for illustration purposes.
> >
> > Thank you again!
> >
> > --
> > View this message in context: http://r.789695.n4.nabble.com/Using-FUNCTION-to-
> create-usable-objects-tp4588681p4589752.html
> > Sent from the R help mailing list archive at Nabble.com.
> >
> > ______________________________________________
> > 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.
> 
> ______________________________________________
> 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