[R] Anova question

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Wed Jun 9 18:07:49 CEST 2004

On Wed, 2004-06-09 at 15:36, Paulo Nuin wrote:
> Hello everyone
> This is my first message to the list and I believe the question I am
> including is a simple one.
> I have a matrix where I need to calculate ANOVA for the rows as the
> columns represent a different treatment. I would like to know if there
> is a command or a series of commans that I can enter to do that. 

let us say x represents the measurements. Further suppose that the first
10 columns represent Treatment A and the next 10 Treatment B.

x <- rnorm(20)                         # simulated value for response
g <- as.factor( rep(c("A", "B"), each=10) ) # treatments

model <- lm(x ~ g)

For more information, see help(lm) and help(aov). The books cited in
these references are pretty good and worth looking into. You might also
find the introductory book on R by Peter Daalgard or online
documentations helpful.

> At the moment I have a external script that extracts each row from the
> matrix, transforms it in a column, another factor columns is add and the
> text file is thrown to Rterm --vanilla.

You do not have to do this manually. You can use the apply function to
apply the ANOVA each row. Example

g <- as.factor( rep(c("A", "B"), each=10) ) # treatments
apply( my.matrix, 1, function(x) {
 model <- lm(x ~ g)

If you have hundreds of rows, then you way just store specific output
(test statistics, p-value) instead of printing it. Example coef(model),

More information about the R-help mailing list