[R] Return value from function with For loop

William Dunlap wdunlap at tibco.com
Mon Apr 17 19:59:33 CEST 2017


A long time ago (before the mid-1990's?) with S or S+
   ff <- function(n){ for(i in 1:n) (i+1)
   op <- ff(3)
would result in 'op' being 4, since a for-loop's value
was the value of the last expression executed in the
body of the loop.  The presence of a 'next' or 'break'
in the loop body would affect the return value.

This made the primitive garbage collection used the time
not work so well and was one reason that for-loops with
lots of iterations ran slowly.  Almost no one used
the return value of a for-loop so, to avoid memory issues,
for was changed to always return NULL.

Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Sun, Apr 16, 2017 at 7:26 PM, Ramnik Bansal <ramnik.bansal at gmail.com> wrote:
> In the code below
>
>
> *ff <- function(n){ for(i in 1:n) (i+1)}*
>
> *n<-3;ff(n)->op;print(op)*
>
> Why doesnt *print(op) * print 4 and instead prints NULL.
> Isnt the last line of code executed is *i+1 * and therefore that should be
> returned instead of NULL
>
> instead if I say
> *ff <- function(n){ (n+1) }*
>
> Then
> *n<-3;ff(n)->op;rm(n);print(op)*
> gives 4 as output.
>
> My question is *Which *is considered as the last line in a functoin for the
> purpsoe of default return ? And under what conditions ?
>
> -Thanks,
> Ramnik
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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