Home > database >  Why are the results of this for loop not stored in this empty vector?
Why are the results of this for loop not stored in this empty vector?

Time:12-27

I don't get why the results from this for loop are not stored in the empty vector zz.

When looking at zz in the environment after running the for loop, I only see the value numeric (empty), I've read about it on Stackflow and tried the solutions but can't fix my problem.

Is there a solution for it?

a <- c(100,101,102,100)
return1 <- diff(a)/a[-length(a)]

zz <- c()

for (i in return1){
  zz[i]<- 100*(i 1) 100
  
}

CodePudding user response:

EDIT: If you want to store values in zz, the index i in zz[i] should be an integer of length 1:length(return1).

Because return1 contains non-rounded numbers, this condition is not satisfied. You can solve around this by introducing a proper index that equals 1 in the first iteration and increases 1 unit with each subsequent iteration.

Hence, the following should work:

a <- c(100,101,102,100)
return1 <- diff(a)/a[-length(a)]

zz <- c()
count <- 0
for (i in return1){
  count <- count   1L
  zz[count]<- 100*(i 1) 100
  
}
  • Related