[R] return object from loop inside a function

Phil Spector spector at stat.berkeley.edu
Wed Jan 26 03:55:58 CET 2011

Nicolas -
    Along with returning a value, the return function passes
control back to the caller of the function.  So any statement
after a return statement will just be ignored.
    In R the way this is handled is by returning a list.  Change




and you can access the two parts like this:

result = UUU(pop,grid.dens)

result$pop        # updated pop
result$grid.dens  # updated grid.dens

Hope this helps.

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu

On Tue, 25 Jan 2011, Nicolas Gutierrez wrote:

> Hi All,
> I have a for loop inside the function and I cannot get UUU to give me an 
> updated grid.dens object when I run the function (it does update when I run 
> just the for loop). Here's a simplified version of my function:
> UUU=function(pop, grid.dens) {
> for (i in 1:10){
> Food=grid.dens[pop$yloc[i],pop$xloc[i]]   #use initial grid.dens values
> Consumed=(pop$weight[i]*0.25)
> Left=Food-Consumed
> grid.dens[pop$yloc[i],pop$xloc[i]]=Left   #update grid.dens values on i
> pop$birth[i]=pop$birth[i]+1
> }
> return(pop)
> return(grid.dens)
> }
> I get an updated pop, but not an updated grid.dens.  What am I doing wrong?
> Thanks!
> Nico
> ______________________________________________
> 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