[R] understanding the FUNCTION function

Ista Zahn istazahn at gmail.com
Thu Apr 26 15:44:29 CEST 2012


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.



More information about the R-help mailing list