[R] extraction of mean square value from ANOVA

Dennis Murphy djmuser at gmail.com
Fri May 20 05:38:30 CEST 2011


Hi:

It's easier to use an apply family function than a loop for this type
of problem, as illustrated below:

# Generate 30 random samples of size 10 from a standard
# normal distribution and put them into a matrix
u <- matrix(rnorm(300), ncol = 10)
a <- factor(rep(1:5, each = 2))
b <- factor(rep(1:2, 5))

# Side note: It's not a good idea to name an object 'c' because a
commonly used function in the base package has that name already, as
in c(1, 3, 5)...

# A function to fit the model and to compute the MSE
# deviance() returns the residual sum of squares in a linear model
meansq <- function(y) {
    m <- lm(y ~ a + b)
    deviance(m)/df.residual(m)
  }

# Apply the function to each row of u; the result is a vector of MSEs
msevec <- apply(u, 1, meansq)
msevec

Note 2: The function works if a and b are in the same environment as
the meansq() function. If you do all of this in the console, there
should be no problem. If you decide to put all of this into a
function, then you need to be more careful.

HTH,
Dennis

On Thu, May 19, 2011 at 6:46 PM, Cheryl Johnson
<johnson.cheryl625 at gmail.com> wrote:
> Hello,
>
> I am randomly generating values and then using an ANOVA table to find the
> mean square value. I would like to form a loop that extracts the mean square
> value from ANOVA in each iteration. Below is an example of what I am doing.
>
> a<-rnorm(10)
> b<-factor(c(1,1,2,2,3,3,4,4,5,5))
> c<-factor(c(1,2,1,2,1,2,1,2,1,2))
>
> mylm<-lm(a~b+c)
> anova(mylm)
>
> Since I would like to use a loop to generate this several times it would be
> helpful to know how to extract the mean square value from ANOVA.
>
> Thanks
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list