title: R: mean when conditions got NA
body: <p>Thanks for the previous posts and professional responses.  I can almost do my analysis, except those conditions with NA.  Here is my <code>data.frame</code> and code used.  Could you mind to teach me how to solve the problem when condition contains NA value?</p>
  
  <pre><code> df1 &lt;- data.frame(A = c(1,2,4, 5), B=c(1,3,NA,1), C=c(1,1,3, NA), D=c(1,1,2,2))
  </code></pre>
  
  <p>Using this code, I get df1 as follows:</p>
  
  <pre><code>  A  B  C D
  1 1  1  1 1
  2 2  3  1 1
  3 4 NA  3 2
  4 5  1 NA 2
  </code></pre>
  
  <p>With the helps from Andrie, Sacha Epskamp and Chase (<a href="https://stackoverflow.com/questions/6138052/r-get-average-column-a-based-on-a-range-of-values-in-column-b">R: get average column A based on a range of values in column B</a>), I got mean values of A when D is between 1 and 3, i.e. 2 in this case, with this code.</p>
  
  <pre><code>mean(df1$A[df1$D&gt;1 &amp; df1$D&lt;3])
  </code></pre>
  
  <p>I got my answer as 4.5 as expected (averge of 4 and 5 in column A).</p>
  
  <p>However, when I replace column D to column C, which contains NA.  My answer could only be NA. while I was expecting to see the answer to be average 1 and 2, by neglecting the 3rd row (larger than 2) and the 4th row (with NA) in column C.</p>
  
  <pre><code>mean(df1$A[df1$C&gt;0 &amp; df1$C&lt;2])
  
  R&gt; NA (i expect the count to be 1.5)
  </code></pre>
  
  <p>I know <code>na.omit</code> can remove all rows with <code>na</code> in any entries in <code>df1</code>. However, I prefer not to do so, as I would also like to get the mean and counts for every columns, when one columns' entry is NA. (e.g. I also want to do mean(df1$A, [is.na(df1$C)]) analysis.</p>
  
  <p>I also tried to test using <code>na.rm=T</code> in the condition part, but R did not recognize it, as now the NA is in the condition part. For instance:</p>
  
  <pre><code>mean(df1$A[df1$C&gt;0 &amp; df1$C&lt;2, na.rm=T])
  
  Error in df1$A[df1$C &gt; 0 &amp; df1$C &lt; 2, na.rm = T] :
    incorrect number of dimensions
  </code></pre>
  
  <p>I believe there are smarter way of doing this.  Pls kindly advice. </p>