title: In R, correlation test between two columns, for each of the groups in a third column
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/14030697/in-r-correlation-test-between-two-columns-for-each-of-the-groups-in-a-third-co">In R, correlation test between two columns, for each of the groups in a third column</a>  </p>
  </blockquote>
  
  
  
  <p>My data frame (g) contains 2 columns with continuous data and other columns with categorical data. I want to test for correlations between the 2 continuous variables, in different groups which are defined by a third column.
  g (157X3000) look like:</p>
  
  <pre><code>     Geno          GDW         GN        M1     M2      M3
  1 SB002XSB012 -17.1597630   52.31961    G/G    C/C     T/T
  3 SB002XSB044  -3.6537657   53.81305    G/G    C/G     G/G
  4 SB002XSB051  -7.8411596   58.05924    A/G    C/C     G/T
  5 SB002XSB067   2.8412103   30.85074    A/G    G/G     G/T
  6 SB002XSB073 -16.0789550  -10.09913    A/A    C/G     G/G
  7 SB002XSB095   0.1759709   10.28837    A/A    G/G     T/T
  </code></pre>
  
  <p>I'm looking for the correlations between GDW and GN in each of the groups as defined by each M. I tried :</p>
  
  <pre><code>q&lt;- function (x) {  
      spl&lt;-split(g[,2:3],x)  
      r&lt;-function(x) { 
          if ((nrow(x[[1]][1]))&gt;2)  
            cor.test(x[[1]][1],x[[1]][2],use="pairwise.complete.obs")[3:4] else Na  
      }  
      cor&lt;- sapply(spl,r)  
  } 
  
  all.cor&lt;- apply(g[,4:ncol(g)],2,q)
  </code></pre>
  
  <p>and got:</p>
  
  <pre><code>Error in if ((nrow(x[[1]][1])) &gt; 2) cor.test(x[[1]][1], x[[1]][2], use = "pairwise.complete.obs")[3:4] else Na : 
    argument is of length zero
  </code></pre>