Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store values in For Loop

Tags:

loops

r

I have a for loop in R in which I want to store the result of each calculation (for all the values looped through). In the for loop a function is called and the output is stored in a variable r in the moment. However, this is overwritten in each successive loop. How could I store the result of each loop through the function and access it afterwards?

Thanks,

example

for (par1 in 1:n) {
var<-function(par1,par2)
c(var,par1)->var2
print(var2)

So print returns every instance of var2 but in var2 only the value for the last n is saved..is there any way to get an array of the data or something?

like image 411
Tim Heinert Avatar asked Jan 11 '23 20:01

Tim Heinert


1 Answers

initialise an empty object and then assign the value by indexing

a <- 0
for (i in 1:10) {
     a[i] <- mean(rnorm(50))
}

print(a)

EDIT:

To include an example with two output variables, in the most basic case, create an empty matrix with the number of columns corresponding to your output parameters and the number of rows matching the number of iterations. Then save the output in the matrix, by indexing the row position in your for loop:

n <- 10
mat <- matrix(ncol=2, nrow=n)

for (i in 1:n) {
    var1 <- function_one(i,par1)
    var2 <- function_two(i,par2)
    mat[i,] <- c(var1,var2)
}

print(mat)

The iteration number i corresponds to the row number in the mat object. So there is no need to explicitly keep track of it.

However, this is just to illustrate the basics. Once you understand the above, it is more efficient to use the elegant solution given by @eddi, especially if you are handling many output variables.

like image 92
TWL Avatar answered Jan 20 '23 15:01

TWL