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

arun smartpink111 at yahoo.com
Sat Feb 15 22:39:27 CET 2014

Hi David,
Check the output of:
lapply(mm,function(x) x) #mm is matrix
lapply(as.data.frame(mm),function(x) x)

  sapply(split(mm,col(mm)),function(x){out <- t.test(x[1:15],x[16:25])$p.value}) 
 #       1         2 
#0.1091573 1.0000000

 sapply(as.data.frame(mm), function(x)  t.test(x[1:15],x[16:25])$p.value)
#       V1        V2 
#0.1091573 1.0000000 


On Saturday, February 15, 2014 3:19 PM, David Romano <dromano at stanford.edu> 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]) ;
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.

Thanks in advance for your help!


    [[alternative HTML version deleted]]

R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list