1

I have been trying to run this code (below here) and I have getting this error:

for(i in 1:length(qid2))
{
  for(j in 1:length(qid))
  {
    if (qid2[i]==qid[i])
    {
        correct.option[i] = aid[j+cid[j]]
        print(correct.option[i])
    }
  }
}

Error in if (qid2[i] == qid[i]) { : missing value where TRUE/FALSE needed

lmo
  • 37,904
  • 9
  • 56
  • 69
Apache11
  • 189
  • 11
  • What does the data look like? Also, it's a good idea to put opening brackets on the same line as the code that sets them up. – alistaire May 16 '16 at 06:36
  • Don't separate `for( ... )` or `if( ... )` and `{` with enter/return; keep them on the same line. `if` and `for` can work without the braces if there's more on the same setup line, so it makes it much easier to accidentally mess up your code. – alistaire May 16 '16 at 06:44
  • this question has been answered at: http://stackoverflow.com/questions/7355187/error-in-if-while-condition-missing-value-where-true-false-needed – pengchy Jul 04 '16 at 02:26

1 Answers1

2

Probably because qid2 and qid are different lengths, so at some point i is larger than the shorter length, so that the comparison involves an element that doesn't exist. Perhaps you meant to compare qid2[i]==qid[j] ? The cat() statement below is an example of how you would debug this sort of thing.

qid2 <- 1:3
qid <- 1:2
for (i in 1:length(qid2)) {
   for(j in 1:length(qid)) {
       cat(i,j,qid[i],qid2[i],"\n")
       if (qid2[i]==qid[i]) {
       }
   }
}
## 1 1 1 1 
## 1 2 1 1 
## 2 1 2 2 
## 2 2 2 2 
## 3 1 NA 3 
## Error in if (qid2[i] == qid[i]) {
##     (from #4) : missing value where TRUE/FALSE needed
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453