title: R Conditional standard deviation
body: <p>I have a large data set and I need to get the standard deviation for the <code>Main</code> column based on the number of rows in other columns. Here is a sample data set:</p>
  
  <pre><code>df1 &lt;- data.frame(
    Main = c(0.33, 0.57, 0.60, 0.51), 
    B = c(NA, NA, 0.09,0.19), 
    C = c(NA, 0.05, 0.07, 0.05), 
    D = c(0.23, 0.26, 0.23, 0.26)
  )
  
  View(df1)
  #   Main    B       C       D  
  # 1 0.33    NA      NA      0.23
  # 2 0.57    NA      0.05    0.26
  # 3 0.60    0.09    0.07    0.23
  # 4 0.51    0.19    0.05    0.26
  </code></pre>
  
  <p>Take column <code>B</code> as an example, since row 1&amp;2 are <code>NA</code>, its standard deviation will be <code>sd(df1[3:4,1])</code>; column <code>C&amp;D</code> will be <code>sd(df1[2:4,1])</code> and <code>sd(df1[1:4,1])</code>. Therefore, the result will be:</p>
  
  <pre><code>#     B       C       D  
  # 1   0.06    0.05    0.12
  </code></pre>
  
  <p>I did the followings but it only returned one number - <code>0.0636</code></p>
  
  <pre><code>df2 &lt;- df1[,-1]!=0
  
  sd(df1[df2,1], na.rm = T)
  </code></pre>
  
  <p>My data set has many more columns, and I'm wondering if there is a more efficient way to get it done? Many thanks!</p>