[R] Data manipulation for random intercept GLMM
Ben Bolker
bolker at ufl.edu
Fri May 2 15:35:32 CEST 2008
Giovanni Petris <GPetris <at> uark.edu> writes:
> > ## Example: Ratings of prime minister (Agresti, Table 12.1, p.494)
> > rating <- matrix(c(794, 86, 150, 570), 2, 2)
> > dimnames(rating) <- list(First = c("approve", "disapprove"),
> + Second = c("approve", "disapprove"))
> > rating
> Second
> First approve disapprove
> approve 794 150
> disapprove 86 570
>
[snip]
>
> > approval <- factor(c("Approve", "Disapprove"),
> + levels = c("Disapprove", "Approve"))
> > survey <- factor(c("First", "Second"))
> > tmp <- data.frame(approval = unlist(expand.grid(approval, approval)),
> + survey = rep(survey, each = 4))
> > rat.df <- cbind(tmp[rep(1:8, rep(rating, 2)), ],
> + id = factor(rep(1:sum(rating), 2)))
> > row.names(rat.df) <- NULL
>
> That does the job, since now I can call lmer:
>
> > m1 <- lmer(approval ~ survey + (1 | id), family = binomial, data = rat.df,
> + method = "Laplace")
>
[snip]
>
> Consider also that the next simplest example is the following, in
> which there are three items on a questionnaire and gender is included
> in the model:
>
> > ### Example: Support for legalizing abortion (Agresti, Table 10.13, p.441)
> > legalize <- matrix(c(342, 440, 26, 25, 6, 14, 21, 18, 11, 14,
> + 32, 47, 19, 22, 356, 457), nr = 2)
> > dimnames(legalize) <- list(Gender = c("Male", "Female"),
> + Three = c(111, 112, 211, 212, 121,
> + 122, 221, 222))
> > legalize
> Three
> Gender 111 112 211 212 121 122 221 222
> Male 342 26 6 21 11 32 19 356
> Female 440 25 14 18 14 47 22 457
>
> (Here '111' means (Yes, Yes, Yes) on the three items, etc.)
>
> How can I tranform elegantly this table into a dataframe that I can
> feed to lmer?
>
I would like to know the answers to this as well. I thought
I was going to be able to get away with as.data.frame.table()
[which is handy and underappreciated], but it doesn't expand
counts.
I hope you get an elegant solution: in the meantime, I guess
my advice is to try to write a reasonably general (if not necessarily
absolutely elegant) function that you can supply your students with.
If they have an expand.table() function, they won't care how complex
it is internally ...
Ben Bolker
More information about the R-help
mailing list