Reshaping matrix (was: [R] fast mkChar)
dmurdoch at pair.com
Wed Jun 9 16:52:19 CEST 2004
On 09 Jun 2004 09:52:27 -0400, Paulo Nuin <nuin at terra.com.br> wrote :
>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.
>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.
Welcome to the list. One suggestion: you should use a subject line
that matches the topic of your question, or your question is likely to
Most of the modelling functions in R assume that data is in a vector.
You can convert a matrix to a vector using the as.numeric() function.
To get the treatments associated with each one, you could apply
as.numeric() to the col() function. You should also convert this to a
factor, for the anova.
> original <- matrix(1:12, 3, 4)
> vector <- as.numeric(original)
> treatments <- as.factor(as.numeric(col(original)))
 1 2 3 4 5 6 7 8 9 10 11 12
 1 1 1 2 2 2 3 3 3 4 4 4
Levels: 1 2 3 4
> anova(lm(vector ~ treatments))
Analysis of Variance Table
Df Sum Sq Mean Sq F value Pr(>F)
treatments 3 135 45 45 2.356e-05 ***
Residuals 8 8 1
Signif. codes: 0 `***' 0.001 `**' 0.01 `*' 0.05 `.' 0.1 ` ' 1
You can read the help pages on each of these functions to see what
options are available.
More information about the R-help