You can certainly use apply()....
#make up some data
x <- 10; y <- 10; g <- 5
set.seed(1969)
dat <- matrix(rnorm((x + y) * g), ncol = x + y)
# apply() the t.test function to each row fo the matrix and extract
just the p value
results <- apply(dat, 1, function(dat) {
t.test(x = dat[1:x], y = dat[(x + 1):(x + y)])$p.value})
# if you want, you can bind p-values back into the matrix
cbind(dat, pvals = results)
HTH,
Josh
P. S. If you are doing this for many rows, the p-values may not be
meaningful in the sense of hypothesis testing (e.g., p < .05 is
"significant")
On Tue, Aug 24, 2010 at 12:09 PM, Cedric Laczny <cedric.laczny at gmx.de>
wrote:> Hi,
>
> the actual thread on "multiple assignments ?" made up an
interesting point for
> me.
> If I have a matrix with g rows and x + y columns where columns 1 - x
contain
> values of group1 and columns x+1 to y contain the values of group2.
> Now I want to compute a vector of length g that holds the p-value (e.g. via
a
> t-test) calculated for the appropriate row in the matrix.
>
> At the moment I am doing something like this:
> # code might be wrong. Should just give the idea.
> p = rep(-1, g)
> for( i in 1: g)
> p[i] = t.test(values[i, c(1:x)], values[i, c(x +1: x+y)]
>
> I am now wondering if there is a faster (maybe also more elegant) way to do
> this, e.g. using something like lapply or such?
>
> Best,
>
> Cedric
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/