[R] Saving output in an iterated function

Economics Guy economics.guy at gmail.com
Sun Jun 21 15:06:19 CEST 2009


# I have a function that takes a few vectors manipulates them and then
outputs a matrix of results:

funct1 <- function(eh,be){
	ce <- eh+be
	data.frame(eh,be,ce)
	}
	
ones <- c(1,1,1)
twos <- c(2,2,2)
funct1(ones,twos)


# I would like to iterate it and save the results from each iteration.
I could of course write a loop but I would like to do this is the most
efficient way possible. The best I have come up with is this:


functM <- function(eh,be,period,endPeriod){
	period <- period+1
	ce <- eh+be
	{if (period < endPeriod)
		functM(ce,be,period,endPeriod)
		else data.frame(eh,be,ce,period)}
	}
	
ones <- c(1,1,1)
twos <- c(2,2,2)
functM(ones,twos,0,4)

# As you can see it only reports the results form the last iteration.
Here it is the 4th iteration, but if you change the last argument of
the previous run of functM, you can see that it will always report the
final matrix. How can I have it save/store/write the results of each
iteration. I do not care if it stacks it all into the same matrix or
if I have to write.csv each time. I just want to do it in the most
efficient way possible (the actual program will run for many many
iterations of large vectors.

# Thanks.




More information about the R-help mailing list