title: Perform t-test using aggregate function in R
body: <p>I'm having difficulty using the unpaired t-test and the aggregate function.  </p>
  
  <p>Example</p>
  
  <pre><code>dd&lt;-data.frame(names=c("1st","1st","1st","1st","2nd","2nd","2nd","2nd"),a=c(11,12,13,14,2.1,2.2,2.3,2.4),b=c(3.1,3.2,3.3,3.4,3.1,3.2,3.3,3.4))
  dd
  #  Compare all the values in the "a" column that match with "1st" against the values in the "b" column that match "1st".  
  #  Then, do the same thing with those matching "2nd"
  
  t.test(c(11,12,13,14),c(3.1,3.2,3.3,3.4))$p.value
  t.test(c(3.1,3.2,3.3,3.4),c(3.1,3.2,3.3,3.4))$p.value
  
  #  Also need to replace any errors from t.test that have too low variance with NA
  #  An example of the type of error I might run into would be if the "b" column was replaced with c(3,3,3,3,3,3,3,3).  
  </code></pre>
  
  <p>For paired data, I found a work around.</p>
  
  <pre><code>#  Create Paired data.
  data_paired&lt;-dd[,3]-dd[,2]
  
  #  Create new t-test so that it doesn't crash upon the first instance of an error.  
  my_t.test&lt;-function(x){
      A&lt;-try(t.test(x), silent=TRUE)
      if (is(A, "try-error")) return(NA) else return(A$p.value)
  }
  
  #  Use aggregate with new t-test.  
  aggregate(data_paired, by=list(dd$name),FUN=my_t.test)
  </code></pre>
  
  <p>This aggregate works with a single column of input.  However, I can't get it to function when I must have several columns go into the function.  </p>
  
  <p>Example:</p>
  
  <pre><code>my_t.test2&lt;-function(x,y){
      A&lt;-try(t.test(x,y,paired=FALSE), silent=TRUE)
      if (is(A, "try-error")) return(NA) else return(A$p.value)
  }
  
  aggregate(dd[,c(2,3)],by=list(dd$name),function(x,y) my_t.test2(dd[,3],dd[,2]))
  </code></pre>
  
  <p>I had thought that the aggregate function would only send the rows matching the value in the list to the function my_t.test2 and then move onto the next list element.  However, the results produced indicate that it is performing a t-test on all values in the column like below.  And then placing each of those values in the results.  </p>
  
  <pre><code>t.test(dd[,3],dd[,2])$p.value
  </code></pre>
  
  <p>What am I missing?  Is this an issues with the original my_test.2, an issue with how to structure the aggregate function, or something else.  The way I applied it doesn't seem to aggregate.  </p>
  
  <p>These are the results I want.</p>
  
  <pre><code>t.test(c(11,12,13,14),c(3.1,3.2,3.3,3.4))$p.value
  t.test(c(3.1,3.2,3.3,3.4),c(3.1,3.2,3.3,3.4))$p.value
  </code></pre>
  
  <p>To Note, this is a toy example and the actual data set will have well over 100,000 entries that need to be grouped by the value in the names column.  Hence why I need the aggregate function.  </p>
  
  <p>Thanks for the help.  </p>