5

I have a mer object created with a called to lmer().

I can obtain the random effects with ranef() but I would also like to have corresponding number of observations for each random effect - is there an easy way to do that ?

Additional Info:

I may not have made myself quite clear above. For example, if I have a simple 2-level model with patients clustered within hospitals and random intercepts for hospitals, I would like to extract the random effects for each hospital with ranef() together with the number of patients within each hospital. At the moment, I use

ranef(fullmodel)[[1]]

which gives me something like:

     (Intercept)
ADE -0.108195883
BEJ -0.005761677
CIS  0.124129426
CMH  0.270879048
CSI  0.285344837
CUL  0.189308979

I would like to get something like:

     (Intercept)  n
ADE -0.108195883  77
BEJ -0.005761677  171
CIS  0.124129426  201
CMH  0.270879048  39
CSI  0.285344837  171
CUL  0.189308979  131

To do this, I have been using

fullmodel <- glmer(.....+(1|hospital), data=dt1)

freqs <- as.data.frame(table(dt1$hospital))
freqs <- freqs[foo$Freq>0,]

And then cbinding this to the results from ranef(fullmodel)[[1]]

However this seems unsophisticated and prone to error.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
Robert Long
  • 5,722
  • 5
  • 29
  • 50

2 Answers2

7

ranef returns a list of matrices corresponding to grouping factors, where the rows in each matrix correspond to observations (factor levels) for a random effect and the columns correspond to random effect variables (intercept, slope etc.). Thus the easiest way to get the numbers of observations is

sapply(ranef(model),nrow)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
3

This command returns the random effects together with frequencies of the random factor levels:

lapply(names(ranef(model)),
       function(x) cbind(ranef(model)[[x]], table(model.frame(model)[[x]])))
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168