Anastasia Tn Anastasia Tn - 12 days ago 8
R Question

Loop in R: how to store the output?

i'm really new to R..and i'm trying to save the output of print(w1) into a matrix (1001x4) (or even in a matrix 4004x1) of the following loop but for me it is impossible. I tried to save w1 into a matrix after print(w1)

b[,i]<-1/n^2*(sum1+n+sum2)
, but it saves only the last 4 outputs. My code is:

n=4
for(a in seq(0,1,0.001)){
for(i in 1:n){
sum1<-0
sum2<-0
for(j in 1:n){
if(j>i){
sum1<-sum1+(n/j)^a
}
else if(j<i){

sum2<-sum2-(n/i)^a


}

}

w1<-1/n^2*(sum1+n+sum2)

print(w1)
#b[,i]<-1/n^2*(sum1+n+sum2)
}

}


Thanks in advance for the help! Anastasia.

Answer

It only stores the last 4 outputs because you are using i as index (which will only be 1 to 4).

If you want to store all the values you will have to append new values to the current vector. You can do so like this:

vec <- c() # Create a new empty vector before the loop
# After print(w1) add
vec <- c(vec, w1) # This will append the new value (w1) to the vector