[R] t-test for multiple variables

Simon Anders anders at ebi.ac.uk
Fri Jul 18 12:37:24 CEST 2008


Hi Henning,

Henning Wildhagen wrote:
> Given a dataframe of three columns, where col1 is of type factor, col 2 and 
> col3 are numeric and pairs of observations i would like to perform a paired 
> t-test for each level of col1.
> I would like to avoid specifying the levels of col1 manually because it 
> seems to me as being stupid, however, i did not figure out how to tell it R 
> in an function. I tried with tapply, but it did not work.

That's what 'tapply' is meant for. Try this:

tapply( 1:nrow(df), df$col1, function(r)
    t.test( df$col2[r], df$col3[r], paired=TRUE  ) )

Here, tapply calls the fucntion in the second line for each level of 
col1, always passing the row indices of the rows with this level as 
parameter 'r'.

HTH
   Simon



More information about the R-help mailing list