[R] understanding the FUNCTION function

R. Michael Weylandt michael.weylandt at gmail.com
Thu Apr 26 20:34:16 CEST 2012


Simply return it like a function is supposed to:

fac <- function(x, loud = TRUE){
    a <- 1
    for(i in seq_len(x)) { # seq_len is faster and more robust
        a <- a * i
        if(loud) print(a)
    }
    return(a)
}

fac3 <- fac(3)

print(fac3) # As desired

Michael

On Thu, Apr 26, 2012 at 2:16 PM, michaelyb <cel81009759 at gmail.com> 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.
>
>
> --
> 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.



More information about the R-help mailing list