Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

r - Store values in For Loop

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...