[R] trouble using sapply to perform multiple t-test

Jim Lemon jim at bitwrit.com.au
Sat Feb 15 21:23:04 CET 2014

On 02/16/2014 07:16 AM, David Romano wrote:
> Hi folks,
> I'm having trouble with code that used to work, and I can't figure out
> what's going wrong.  I'd be grateful for any help in sorting this out.
> Suppose I define a matrix
>> mm<- matrix(1:15, 25,2)
> and compare the first 15 values of column 1 of mm to the values remaining
> in the same column and obtain p values as follows:
>> c1<- mm[,1]
>> out<- t.test(c1[1:15],c1[16:25]) ; out$p.value
> This of course works fine, but if I try to embed this line in a call to
> sapply to repeat this for each column, I get the following:
>> mm.pvals<- sapply(mm, function(x) {out<- t.test(x[1:15],x[16:25]) ;
> out$p.value})
> Error in t.test.default(x[1:15], x[16:25]) : not enough 'x' observations
> What is baffling is code like this has worked for me before, and I can't
> tell what's triggering the error.
Hi David,
You have here the old "s" problem. I suspect that you previously ran 
this code on a data frame, not a matrix. Try this:

  function(x) {out <- t.test(x[1:15],x[16:25]);out$p.value})


More information about the R-help mailing list