[R] understanding the FUNCTION function

David Winsemius dwinsemius at comcast.net
Thu Apr 26 20:34:42 CEST 2012


On Apr 26, 2012, at 2:16 PM, michaelyb wrote:

> Ista,
>
> Since you seem to know your stuff very well, how would you get 120  
> out of a
> function that gives you the factorial of 5, without using  
> factorial(5)?
>
>> Meanwhile, look at this example instead:
>> fac<-function(x){a<-1
>>                for(i in 1:x){
>>                a<-a*i
>>                print(a)}}
>
> gives you 120, but you cannot access it after the end of execution.

Right. So learn to avoid depending on `print` for its side-effects:

fac<-function(x){a<-1
                 for(i in 1:x){
                 a<-a*i
                        }
                 return(a)}
  fac(5)
[1] 120

>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-FUNCTION-to-create-usable-objects-tp4588681p4590549.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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list