0

I have trouble when I make the double for loop for a huge list, the code is like:

bootk=0
bias=0
Nk=0
#datalist = list()
for (i in 1:ksign){
for (j in 1:boottime){
    if (i<=ksign1[j]){
        bias[i]=bias[i]+(bigmatrix[,j]$V1.x[i]-bigmatrix[,j]$V1.y[i])
        Nk[i]=Nk[i]+1
        
      }
    }
  }

ksign and boottime are just 2 numbers here. bigmatrix is like a huge list:

          [,1]          [,2]          [,3]          [,4]          [,5]         
Row.names Character,269 Character,266 Character,283 Character,273 Character,270
V1.x      Numeric,269   Numeric,266   Numeric,283   Numeric,273   Numeric,270  
V2.x      Numeric,269   Numeric,266   Numeric,283   Numeric,273   Numeric,270  
V1.y      Numeric,269   Numeric,266   Numeric,283   Numeric,273   Numeric,270  
V2.y      Numeric,269   Numeric,266   Numeric,283   Numeric,273   Numeric,270  

which is a combination of several list depends on the value of boottime. Here I defined it as 5. But after I ran the code, the output is like:

bias
  [1] 2.521886       NA       NA       NA       NA       NA       NA       NA
  [9]       NA       NA       NA       NA       NA       NA       NA       NA
 [17]       NA       NA       NA       NA       NA       NA       NA       NA
 [25]       NA       NA       NA       NA       NA       NA       NA       NA
 [33]       NA       NA       NA       NA       NA       NA       NA       NA

I should have a list of bias, which the number is the value of ksign. What happened here? Any ideas?

misaya li
  • 25
  • 5
  • 1
    Hard to say without seeing the data, but you probably have `NA`s in your big matrix or you are indexing out of range. E.g.if `y <- 1:9` then `y[10]` returns `NA`. – Ari Anisfeld Aug 27 '20 at 04:51
  • 2
    Make a small, reproducible example of dimension 2x4 to demonstrate what is going wrong. This will help you understand the problem better and help us help you. You could also manually set `i` and `j` to 1 and 2, respectively and see what the calculating expressions returns. This way, you can "manually" debug what is going on. – Roman Luštrik Aug 27 '20 at 06:34
  • Read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610 – jay.sf Aug 27 '20 at 09:43

1 Answers1

0

The problem is that bias is not initialized as a vector, but as a scalar:

bias <- 0
bias[1] <- bias[1] + 2  # ok: bias[1] == bias
bias[2] <- bias[2] + 3  # not ok: bias[2] is uninitialized and thus NA

results in (2 NA) for bias.

cdalitz
  • 1,019
  • 1
  • 6
  • 7