title: taking the sum of a TRUE/FALSE vector in r
body: <p>I am working analyzing SNP data for a fungus, and I am trying to impute the missing data by changing the Ns to the genotype of the more frequent allele....see below. 
  newdata is a matrix of my snps (rows)and fungal isolates(columns). The genotypes for each snp are in the 0, 1, and N format, and that is why I am trying to impute the missing genotypes.</p>
  
  <pre><code>newdata_imputed=newdata
  for (k in 1:nrow(newdata)){
  u=newdata[k,]
  x&lt;-sum(u==0)
  y&lt;-sum(u==1)
  all_freq=y/(x+y)
  if (all_freq&lt;0.5){
  newdata_imputed[k,]=gsub("N",0,u)
  } else{newdata_imputed[k,]=gsub("N",1,u)}
  print(k)
  }
  </code></pre>
  
  <p>However, I keep getting this error:</p>
  
  <pre><code>[1] 295
  [1] 296
  Error in if (all_freq &lt; 0.5) { : missing value where TRUE/FALSE needed
  </code></pre>
  
  <p>It is obvious that the code runs but stops after encountering a problem. Please, can someone tell me what I am doing wrong? I am a newbie to R, and any advice would be greatly appreciated.</p>
  
  <p>@akrun, the reason why i used a for loop is because it is nested in another for loop..so after using your code. </p>
  
  <pre><code>newdata=as.data.frame(newdata)
  u=newdata
  all_freq &lt;- rowSums(u==1)/rowSums((u==1)|(u==0))
  indx &lt;- all_freq &lt; 0.5
  indx1 &lt;-  indx &amp; !is.na(indx)
  indx2 &lt;- !indx &amp; !is.na(indx)
  newdata[indx1,] &lt;- lapply(newdata[indx1,], gsub, pattern='N', replacement=0)
  newdata[indx2,] &lt;- lapply(newdata[indx2,], gsub, pattern='N', replacement=1)
  newdata[] &lt;- lapply(newdata, as.numeric)
  </code></pre>
  
  <p>I got weird values</p>
  
  <pre><code>newdata[1:10,1:10]
     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
  1   3  3  3  3  3  3  3  3  3   3
  2   2  2  2  2  2  2  2  2  2   2
  3   3  3  3  3  3  3  3  3  3   3
  4   1  1  1  1  1  1  1  1  1   1
  </code></pre>
  
  <p>Please where is the "3" coming from.???? I should only have 0 or 1    </p>