SCM

SCM Repository

[matrix] Annotation of /pkg/R/lmer.R
ViewVC logotype

Annotation of /pkg/R/lmer.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 902 - (view) (download)

1 : bates 767 # Methods for lmer and for the objects that it produces
2 : bates 689
3 :     ## Some utilities
4 :    
5 : bates 775 ## Return the index into the packed lower triangle
6 : bates 689 Lind <- function(i,j) {
7 :     if (i < j) stop(paste("Index i=", i,"must be >= index j=", j))
8 :     ((i - 1) * i)/2 + j
9 : bates 446 }
10 :    
11 : bates 775 ## Return the pairs of expressions separated by vertical bars
12 : bates 769 findbars <- function(term)
13 :     {
14 :     if (is.name(term) || is.numeric(term)) return(NULL)
15 :     if (term[[1]] == as.name("(")) return(findbars(term[[2]]))
16 :     if (!is.call(term)) stop("term must be of class call")
17 :     if (term[[1]] == as.name('|')) return(term)
18 :     if (length(term) == 2) return(findbars(term[[2]]))
19 :     c(findbars(term[[2]]), findbars(term[[3]]))
20 :     }
21 :    
22 : bates 775 ## Return the formula omitting the pairs of expressions
23 :     ## that are separated by vertical bars
24 : bates 769 nobars <- function(term)
25 :     {
26 :     # FIXME: is the is.name in the condition redundant?
27 :     # A name won't satisfy the first condition.
28 :     if (!('|' %in% all.names(term)) || is.name(term)) return(term)
29 :     if (is.call(term) && term[[1]] == as.name('|')) return(NULL)
30 :     if (length(term) == 2) {
31 :     nb <- nobars(term[[2]])
32 :     if (is.null(nb)) return(NULL)
33 :     term[[2]] <- nb
34 :     return(term)
35 :     }
36 :     nb2 <- nobars(term[[2]])
37 :     nb3 <- nobars(term[[3]])
38 :     if (is.null(nb2)) return(nb3)
39 :     if (is.null(nb3)) return(nb2)
40 :     term[[2]] <- nb2
41 :     term[[3]] <- nb3
42 :     term
43 :     }
44 :    
45 : bates 775 ## Substitute the '+' function for the '|' function
46 : bates 769 subbars <- function(term)
47 :     {
48 :     if (is.name(term) || is.numeric(term)) return(term)
49 :     if (length(term) == 2) {
50 :     term[[2]] <- subbars(term[[2]])
51 :     return(term)
52 :     }
53 :     stopifnot(length(term) == 3)
54 : maechler 832 if (is.call(term) && term[[1]] == as.name('|'))
55 :     term[[1]] <- as.name('+')
56 : bates 769 term[[2]] <- subbars(term[[2]])
57 :     term[[3]] <- subbars(term[[3]])
58 :     term
59 :     }
60 : bates 824
61 :     abbrvNms <- function(gnm, cnms)
62 :     {
63 :     ans <- paste(abbreviate(gnm), abbreviate(cnms), sep = '.')
64 :     if (length(cnms) > 1) {
65 :     anms <- lapply(cnms, abbreviate, minlength = 3)
66 :     nmmat <- outer(anms, anms, paste, sep = '.')
67 :     ans <- c(ans, paste(abbreviate(gnm, minlength = 3),
68 :     nmmat[upper.tri(nmmat)], sep = '.'))
69 :     }
70 :     ans
71 :     }
72 :    
73 : bates 775 ## Control parameters for lmer
74 :     lmerControl <-
75 : maechler 832 function(maxIter = 200, # used in ../src/lmer.c only
76 : bates 888 tolerance = sqrt(.Machine$double.eps),# ditto
77 : bates 769 msMaxIter = 200,
78 : maechler 832 ## msTol = sqrt(.Machine$double.eps),
79 :     ## FIXME: should be able to pass tolerances to nlminb()
80 :     msVerbose = getOption("verbose"),
81 : bates 752 niterEM = 15,
82 : bates 435 EMverbose = getOption("verbose"),
83 : maechler 843 PQLmaxIt = 30,# FIXME: unused; PQL currently uses 'maxIter' instead
84 : bates 435 analyticGradient = TRUE,
85 : maechler 832 analyticHessian = FALSE # unused _FIXME_
86 :     )
87 : bates 435 {
88 : bates 775 list(maxIter = as.integer(maxIter),
89 : maechler 832 tolerance = as.double(tolerance),
90 : bates 775 msMaxIter = as.integer(msMaxIter),
91 : maechler 832 ## msTol = as.double(msTol),
92 :     msVerbose = as.integer(msVerbose),# "integer" on purpose
93 : bates 775 niterEM = as.integer(niterEM),
94 : maechler 832 EMverbose = as.logical(EMverbose),
95 : bates 775 PQLmaxIt = as.integer(PQLmaxIt),
96 :     analyticGradient = as.logical(analyticGradient),
97 :     analyticHessian = as.logical(analyticHessian))
98 : bates 435 }
99 :    
100 : bates 755 setMethod("lmer", signature(formula = "formula"),
101 : bates 689 function(formula, data, family,
102 :     method = c("REML", "ML", "PQL", "Laplace", "AGQ"),
103 : bates 901 control = list(), start,
104 : bates 435 subset, weights, na.action, offset,
105 : maechler 832 model = TRUE, x = FALSE, y = FALSE , ...)
106 :     ## x, y : not dealt with at all -- FIXME ? .NotYetImplemented(
107 :     {
108 :     ## match and check parameters
109 : bates 755 if (length(formula) < 3) stop("formula must be a two-sided formula")
110 :     cv <- do.call("lmerControl", control)
111 :     ## evaluate glm.fit, a generalized linear fit of fixed effects only
112 : maechler 832 mf <- match.call()
113 : bates 755 m <- match(c("family", "data", "subset", "weights",
114 :     "na.action", "offset"), names(mf), 0)
115 :     mf <- mf[c(1, m)]
116 :     frame.form <- subbars(formula) # substitute `+' for `|'
117 :     fixed.form <- nobars(formula) # remove any terms with `|'
118 : bates 767 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
119 : bates 755 fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
120 :     environment(fixed.form) <- environment(frame.form) <- environment(formula)
121 :     mf$formula <- fixed.form
122 :     mf$x <- mf$model <- mf$y <- TRUE
123 :     mf[[1]] <- as.name("glm")
124 :     glm.fit <- eval(mf, parent.frame())
125 : bates 767 x <- glm.fit$x
126 :     y <- as.double(glm.fit$y)
127 : maechler 832 lmm <- missing(family) # => linear mixed model
128 : bates 769 family <- glm.fit$family
129 : bates 449
130 : maechler 832 if (lmm) { # linear mixed model
131 :     method <- match.arg(method)
132 :     if (method %in% c("PQL", "Laplace", "AGQ")) {
133 :     warning(paste('Argument method = "', method,
134 :     '" is not meaningful for a linear mixed model.\n',
135 :     'Using method = "REML".\n', sep = ''))
136 :     method <- "REML"
137 :     }
138 :     } else { # generalized linear mixed model
139 :     if (missing(method)) method <- "PQL"
140 :     else {
141 :     method <- match.arg(method)
142 :    
143 :     ## <FIXME>: only
144 :     ## if( !(family == "gaussian" && link == "identity") ) {
145 :     if (method == "ML") method <- "PQL"
146 :     if (method == "REML")
147 :     warning('Argument method = "REML" is not meaningful ',
148 :     'for a generalized linear mixed model.',
149 :     '\nUsing method = "PQL".\n')
150 :     ## } </FIXME>
151 :     }
152 :     }
153 :    
154 : bates 755 ## evaluate a model frame for fixed and random effects
155 : bates 435 mf$formula <- frame.form
156 : bates 755 mf$x <- mf$model <- mf$y <- mf$family <- NULL
157 : bates 435 mf$drop.unused.levels <- TRUE
158 : bates 755 mf[[1]] <- as.name("model.frame")
159 : bates 435 frm <- eval(mf, parent.frame())
160 : bates 755
161 : bates 435 ## grouping factors and model matrices for random effects
162 :     bars <- findbars(formula[[3]])
163 : maechler 832 random <-
164 :     lapply(bars, function(x)
165 :     list(model.matrix(eval(substitute(~ T, list(T = x[[2]]))),
166 :     frm),
167 :     eval(substitute(as.factor(fac)[,drop = TRUE],
168 :     list(fac = x[[3]])), frm)))
169 : bates 435 names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
170 : bates 755
171 : bates 435 ## order factor list by decreasing number of levels
172 : bates 449 nlev <- sapply(random, function(x) length(levels(x[[2]])))
173 : bates 452 if (any(diff(nlev) > 0)) {
174 : bates 449 random <- random[rev(order(nlev))]
175 : bates 435 }
176 : bates 767
177 :     ## Create the model matrices and a mixed-effects representation (mer)
178 : bates 435 mmats <- c(lapply(random, "[[", 1),
179 : bates 755 .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
180 :     mer <- .Call("lmer_create", lapply(random, "[[", 2),
181 :     mmats, method, PACKAGE = "Matrix")
182 : bates 767 if (lmm) { ## linear mixed model
183 : bates 901 if (missing(start)) .Call("lmer_initial", mer, PACKAGE="Matrix")
184 :     else .Call("lmer_set_initial", mer, start, PACKAGE = "Matrix")
185 : bates 755 .Call("lmer_ECMEsteps", mer, cv$niterEM, cv$EMverbose, PACKAGE = "Matrix")
186 :     LMEoptimize(mer) <- cv
187 :     fits <- .Call("lmer_fitted", mer, mmats, TRUE, PACKAGE = "Matrix")
188 : bates 767 return(new("lmer",
189 : bates 769 mer,
190 : bates 767 assign = attr(x, "assign"),
191 :     call = match.call(),
192 : bates 769 family = family, fitted = fits,
193 :     fixed = fixef(mer),
194 :     frame = if (model) frm else data.frame(),
195 :     logLik = logLik(mer),
196 : bates 755 residuals = unname(model.response(frm) - fits),
197 : bates 769 terms = glm.fit$terms))
198 : bates 755 }
199 :    
200 :     ## The rest of the function applies to generalized linear mixed models
201 :     gVerb <- getOption("verbose")
202 : bates 776 eta <- glm.fit$linear.predictors
203 : bates 767 wts <- glm.fit$prior.weights
204 : bates 774 wtssqr <- wts * wts
205 : bates 767 offset <- glm.fit$offset
206 :     if (is.null(offset)) offset <- numeric(length(eta))
207 : bates 776 mu <- numeric(length(eta))
208 : bates 767
209 : bates 774 dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
210 : bates 767 linkinv <- quote(family$linkinv(eta))
211 :     mu.eta <- quote(family$mu.eta(eta))
212 :     variance <- quote(family$variance(mu))
213 : bates 775 LMEopt <- get("LMEoptimize<-")
214 :     doLMEopt <- quote(LMEopt(x = mer, value = cv))
215 : bates 767
216 : bates 809 GSpt <- .Call("glmer_init", environment(), PACKAGE = "Matrix")
217 :     .Call("glmer_PQL", GSpt, PACKAGE = "Matrix") # obtain PQL estimates
218 : bates 755
219 : bates 774 fixInd <- seq(ncol(x))
220 :     ## pars[fixInd] == beta, pars[-fixInd] == theta
221 :     PQLpars <- c(fixef(mer),
222 :     .Call("lmer_coef", mer, 2, PACKAGE = "Matrix"))
223 : bates 775 ## set flag to skip fixed-effects in subsequent calls
224 :     mer@nc[length(mmats)] <- -mer@nc[length(mmats)]
225 : bates 777 ## indicator of constrained parameters
226 :     const <- c(rep(FALSE, length(fixInd)),
227 :     unlist(lapply(mer@nc[seq(along = random)],
228 :     function(k) 1:((k*(k+1))/2) <= k)
229 :     ))
230 : bates 779 devAGQ <- function(pars, n)
231 :     .Call("glmer_devAGQ", pars, GSpt, n, PACKAGE = "Matrix")
232 : maechler 832
233 : bates 801 deviance <- devAGQ(PQLpars, 1)
234 : bates 804 ### FIXME: For nf == 1 change this to an AGQ evaluation. Needs
235 : bates 801 ### AGQ for nc > 1 first.
236 : bates 777 fxd <- PQLpars[fixInd]
237 : bates 779 loglik <- logLik(mer)
238 : bates 775
239 : bates 777 if (method %in% c("Laplace", "AGQ")) {
240 : bates 779 nAGQ <- 1
241 :     if (method == "AGQ") { # determine nAGQ at PQL estimates
242 :     dev11 <- devAGQ(PQLpars, 11)
243 : bates 799 ## FIXME: Should this be an absolute or a relative tolerance?
244 : bates 779 devTol <- sqrt(.Machine$double.eps) * abs(dev11)
245 : bates 799 for (nAGQ in c(9, 7, 5, 3, 1))
246 : bates 779 if (abs(dev11 - devAGQ(PQLpars, nAGQ - 2)) > devTol) break
247 : bates 799 nAGQ <- nAGQ + 2
248 :     if (gVerb)
249 :     cat(paste("Using", nAGQ, "quadrature points per column\n"))
250 : bates 779 }
251 :     obj <- function(pars)
252 :     .Call("glmer_devAGQ", pars, GSpt, nAGQ, PACKAGE = "Matrix")
253 : bates 777 if (exists("nlminb", mode = "function")) {
254 : bates 755 optimRes <-
255 : bates 779 nlminb(PQLpars, obj,
256 : bates 755 lower = ifelse(const, 5e-10, -Inf),
257 :     control = list(trace = getOption("verbose"),
258 : maechler 832 iter.max = cv$msMaxIter))
259 : bates 755 optpars <- optimRes$par
260 :     if (optimRes$convergence != 0)
261 :     warning("nlminb failed to converge")
262 : bates 779 deviance <- optimRes$objective
263 : bates 755 } else {
264 :     optimRes <-
265 : bates 779 optim(PQLpars, obj, method = "L-BFGS-B",
266 : bates 755 lower = ifelse(const, 5e-10, -Inf),
267 :     control = list(trace = getOption("verbose"),
268 : bates 776 maxit = cv$msMaxIter))
269 : bates 755 optpars <- optimRes$par
270 :     if (optimRes$convergence != 0)
271 :     warning("optim failed to converge")
272 : bates 779 deviance <- optimRes$value
273 : bates 755 }
274 : bates 774 if (gVerb) {
275 : bates 772 cat(paste("convergence message", optimRes$message, "\n"))
276 : bates 777 }
277 :     fxd[] <- optpars[fixInd] ## preserve the names
278 : bates 809 .Call("lmer_coefGets", mer, optpars[-fixInd], 2, PACKAGE = "Matrix")
279 : bates 755 }
280 :    
281 : bates 776 .Call("glmer_finalize", GSpt, PACKAGE = "Matrix")
282 : bates 779 loglik[] <- -deviance/2
283 : maechler 832 new("lmer", mer,
284 :     frame = if (model) frm else data.frame(),
285 :     terms = glm.fit$terms,
286 : bates 777 assign = attr(glm.fit$x, "assign"),
287 :     call = match.call(), family = family,
288 :     logLik = loglik, fixed = fxd)
289 : bates 435 })
290 : maechler 832 ## end{ "lmer . formula " }
291 : bates 435
292 : bates 755 setReplaceMethod("LMEoptimize", signature(x="mer", value="list"),
293 : bates 316 function(x, value)
294 :     {
295 :     if (value$msMaxIter < 1) return(x)
296 :     nc <- x@nc
297 : bates 755 constr <- unlist(lapply(nc[1:(length(nc) - 2)],
298 :     function(k) 1:((k*(k+1))/2) <= k))
299 : bates 752 fn <- function(pars)
300 : bates 755 deviance(.Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix"))
301 : maechler 832 gr <-
302 :     if (value$analyticGradient)
303 : bates 755 function(pars) {
304 :     if (!isTRUE(all.equal(pars,
305 :     .Call("lmer_coef", x,
306 :     2, PACKAGE = "Matrix"))))
307 :     .Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix")
308 :     .Call("lmer_gradient", x, 2, PACKAGE = "Matrix")
309 :     }
310 : maechler 832 ## else NULL
311 :     optimRes <-
312 :     if (exists("nlminb", mode = "function"))
313 :     nlminb(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
314 :     fn, gr,
315 :     lower = ifelse(constr, 5e-10, -Inf),
316 :     control = list(iter.max = value$msMaxIter,
317 :     trace = as.integer(value$msVerbose)))
318 :     else
319 :     optim(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
320 :     fn, gr, method = "L-BFGS-B",
321 :     lower = ifelse(constr, 5e-10, -Inf),
322 :     control = list(maxit = value$msMaxIter,
323 :     trace = as.integer(value$msVerbose)))
324 : bates 755 .Call("lmer_coefGets", x, optimRes$par, 2, PACKAGE = "Matrix")
325 : bates 316 if (optimRes$convergence != 0) {
326 : bates 777 warning(paste("optim or nlminb returned message",
327 :     optimRes$message,"\n"))
328 : bates 316 }
329 :     return(x)
330 :     })
331 :    
332 : bates 413 setMethod("ranef", signature(object = "lmer"),
333 : bates 689 function(object, accumulate = FALSE, ...) {
334 :     val <- new("lmer.ranef",
335 :     lapply(.Call("lmer_ranef", object, PACKAGE = "Matrix"),
336 :     data.frame, check.names = FALSE),
337 :     varFac = object@bVar,
338 :     stdErr = .Call("lmer_sigma", object,
339 : bates 755 object@method == "REML", PACKAGE = "Matrix"))
340 : bates 689 if (!accumulate || length(val@varFac) == 1) return(val)
341 :     ## check for nested factors
342 :     L <- object@L
343 :     if (any(sapply(seq(a = val), function(i) length(L[[Lind(i,i)]]@i))))
344 :     error("Require nested grouping factors to accumulate random effects")
345 :     val
346 : bates 316 })
347 :    
348 : bates 755 setMethod("fixef", signature(object = "mer"),
349 : bates 774 function(object, ...)
350 :     .Call("lmer_fixef", object, PACKAGE = "Matrix"))
351 : bates 316
352 : bates 769 setMethod("fixef", signature(object = "lmer"),
353 :     function(object, ...) object@fixed)
354 : deepayan 721
355 : bates 413 setMethod("VarCorr", signature(x = "lmer"),
356 : bates 902 ##FIXME - change this for reasonable defaults of useScale according to
357 :     ##the family slot.
358 : bates 316 function(x, REML = TRUE, useScale = TRUE, ...) {
359 : bates 550 val <- .Call("lmer_variances", x, PACKAGE = "Matrix")
360 : bates 316 for (i in seq(along = val)) {
361 :     dimnames(val[[i]]) = list(x@cnames[[i]], x@cnames[[i]])
362 :     val[[i]] = as(as(val[[i]], "pdmatrix"), "corrmatrix")
363 :     }
364 :     new("VarCorr",
365 : bates 449 scale = .Call("lmer_sigma", x, REML, PACKAGE = "Matrix"),
366 : bates 316 reSumry = val,
367 :     useScale = useScale)
368 :     })
369 :    
370 : bates 413 setMethod("gradient", signature(x = "lmer"),
371 : bates 755 function(x, unconst, ...)
372 :     .Call("lmer_gradient", x, unconst, PACKAGE = "Matrix"))
373 : bates 316
374 : bates 449 setMethod("summary", signature(object = "lmer"),
375 :     function(object, ...)
376 : bates 769 new("summary.lmer", object,
377 : bates 727 showCorrelation = TRUE,
378 : bates 769 useScale = !((object@family)$family %in% c("binomial", "poisson"))))
379 : bates 316
380 : bates 449 setMethod("show", signature(object = "lmer"),
381 :     function(object)
382 : bates 769 show(new("summary.lmer", object,
383 : bates 727 showCorrelation = FALSE,
384 : bates 769 useScale = !((object@family)$family %in% c("binomial", "poisson")))))
385 : maechler 832
386 : bates 449 setMethod("show", "summary.lmer",
387 : bates 316 function(object) {
388 : bates 727 fcoef <- object@fixed
389 : bates 449 useScale <- object@useScale
390 :     corF <- as(as(vcov(object, useScale = useScale), "pdmatrix"),
391 : bates 316 "corrmatrix")
392 :     DF <- getFixDF(object)
393 :     coefs <- cbind(fcoef, corF@stdDev, DF)
394 :     nc <- object@nc
395 :     dimnames(coefs) <-
396 :     list(names(fcoef), c("Estimate", "Std. Error", "DF"))
397 : bates 449 digits <- max(3, getOption("digits") - 2)
398 : bates 755 REML <- object@method == "REML"
399 : bates 727 llik <- object@logLik
400 : bates 449 dev <- object@deviance
401 : maechler 832
402 : bates 449 rdig <- 5
403 : bates 727 if (glz <- !(object@method %in% c("REML", "ML"))) {
404 :     cat(paste("Generalized linear mixed model fit using",
405 :     object@method, "\n"))
406 :     } else {
407 :     cat("Linear mixed-effects model fit by ")
408 : bates 755 cat(if(REML) "REML\n" else "maximum likelihood\n")
409 : bates 727 }
410 : bates 449 if (!is.null(object@call$formula)) {
411 :     cat("Formula:", deparse(object@call$formula),"\n")
412 :     }
413 :     if (!is.null(object@call$data)) {
414 :     cat(" Data:", deparse(object@call$data), "\n")
415 :     }
416 :     if (!is.null(object@call$subset)) {
417 :     cat(" Subset:",
418 :     deparse(asOneSidedFormula(object@call$subset)[[2]]),"\n")
419 :     }
420 : bates 727 if (glz) {
421 : bates 750 cat(" Family: ", object@family$family, "(",
422 :     object@family$link, " link)\n", sep = "")
423 : bates 727 print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
424 : bates 449 logLik = c(llik),
425 : bates 727 deviance = -2*llik,
426 :     row.names = ""))
427 :     } else {
428 :     print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
429 :     logLik = c(llik),
430 : bates 750 MLdeviance = dev["ML"],
431 : bates 449 REMLdeviance = dev["REML"],
432 :     row.names = ""))
433 : bates 727 }
434 : bates 449 cat("Random effects:\n")
435 : bates 777 show(VarCorr(object, useScale = useScale))
436 : bates 449 ngrps <- lapply(object@flist, function(x) length(levels(x)))
437 :     cat(sprintf("# of obs: %d, groups: ", object@nc[length(object@nc)]))
438 :     cat(paste(paste(names(ngrps), ngrps, sep = ", "), collapse = "; "))
439 :     cat("\n")
440 :     if (!useScale)
441 :     cat("\nEstimated scale (compare to 1) ",
442 : bates 755 .Call("lmer_sigma", object, FALSE, PACKAGE = "Matrix"),
443 : bates 449 "\n")
444 :     if (nrow(coefs) > 0) {
445 :     if (useScale) {
446 :     stat <- coefs[,1]/coefs[,2]
447 :     pval <- 2*pt(abs(stat), coefs[,3], lower = FALSE)
448 :     nms <- colnames(coefs)
449 :     coefs <- cbind(coefs, stat, pval)
450 :     colnames(coefs) <- c(nms, "t value", "Pr(>|t|)")
451 :     } else {
452 :     coefs <- coefs[, 1:2, drop = FALSE]
453 :     stat <- coefs[,1]/coefs[,2]
454 :     pval <- 2*pnorm(abs(stat), lower = FALSE)
455 :     nms <- colnames(coefs)
456 :     coefs <- cbind(coefs, stat, pval)
457 :     colnames(coefs) <- c(nms, "z value", "Pr(>|z|)")
458 :     }
459 :     cat("\nFixed effects:\n")
460 :     printCoefmat(coefs, tst.ind = 4, zap.ind = 3)
461 :     if (length(object@showCorrelation) > 0 && object@showCorrelation[1]) {
462 :     rn <- rownames(coefs)
463 :     dimnames(corF) <- list(
464 :     abbreviate(rn, minlen=11),
465 :     abbreviate(rn, minlen=6))
466 :     if (!is.null(corF)) {
467 :     p <- NCOL(corF)
468 :     if (p > 1) {
469 :     cat("\nCorrelation of Fixed Effects:\n")
470 :     corF <- format(round(corF, 3), nsmall = 3)
471 :     corF[!lower.tri(corF)] <- ""
472 :     print(corF[-1, -p, drop=FALSE], quote = FALSE)
473 :     }
474 :     }
475 :     }
476 :     }
477 :     invisible(object)
478 : bates 316 })
479 :    
480 :     ## calculates degrees of freedom for fixed effects Wald tests
481 :     ## This is a placeholder. The answers are generally wrong. It will
482 :     ## be very tricky to decide what a 'right' answer should be with
483 :     ## crossed random effects.
484 :    
485 : bates 413 setMethod("getFixDF", signature(object="lmer"),
486 : bates 316 function(object, ...)
487 :     {
488 :     nc <- object@nc[-seq(along = object@Omega)]
489 : bates 777 p <- abs(nc[1]) - 1
490 : bates 316 n <- nc[2]
491 :     rep(n-p, p)
492 :     })
493 :    
494 : bates 755 setMethod("logLik", signature(object="mer"),
495 :     function(object, REML = object@method == "REML", ...) {
496 : bates 446 val <- -deviance(object, REML = REML)/2
497 :     nc <- object@nc[-seq(a = object@Omega)]
498 :     attr(val, "nall") <- attr(val, "nobs") <- nc[2]
499 : bates 782 attr(val, "df") <- abs(nc[1]) +
500 : bates 755 length(.Call("lmer_coef", object, 0, PACKAGE = "Matrix"))
501 : maechler 832 attr(val, "REML") <- REML
502 : bates 446 class(val) <- "logLik"
503 :     val
504 :     })
505 :    
506 : bates 769 setMethod("logLik", signature(object="lmer"),
507 :     function(object, ...) object@logLik)
508 : deepayan 721
509 : bates 446 setMethod("anova", signature(object = "lmer"),
510 :     function(object, ...)
511 :     {
512 :     mCall <- match.call(expand.dots = TRUE)
513 :     dots <- list(...)
514 :     modp <- logical(0)
515 :     if (length(dots))
516 :     modp <- sapply(dots, inherits, "lmer") | sapply(dots, inherits, "lm")
517 :     if (any(modp)) { # multiple models - form table
518 :     opts <- dots[!modp]
519 :     mods <- c(list(object), dots[modp])
520 :     names(mods) <- sapply(as.list(mCall)[c(FALSE, TRUE, modp)], as.character)
521 :     mods <- mods[order(sapply(lapply(mods, logLik, REML = FALSE), attr, "df"))]
522 :     calls <- lapply(mods, slot, "call")
523 :     data <- lapply(calls, "[[", "data")
524 :     if (any(data != data[[1]])) stop("all models must be fit to the same data object")
525 :     header <- paste("Data:", data[[1]])
526 :     subset <- lapply(calls, "[[", "subset")
527 :     if (any(subset != subset[[1]])) stop("all models must use the same subset")
528 :     if (!is.null(subset[[1]]))
529 :     header <-
530 :     c(header, paste("Subset", deparse(subset[[1]]), sep = ": "))
531 :     llks <- lapply(mods, logLik, REML = FALSE)
532 :     Df <- sapply(llks, attr, "df")
533 :     llk <- unlist(llks)
534 :     chisq <- 2 * pmax(0, c(NA, diff(llk)))
535 :     dfChisq <- c(NA, diff(Df))
536 :     val <- data.frame(Df = Df,
537 :     AIC = sapply(llks, AIC),
538 :     BIC = sapply(llks, BIC),
539 :     logLik = llk,
540 :     "Chisq" = chisq,
541 :     "Chi Df" = dfChisq,
542 :     "Pr(>Chisq)" = pchisq(chisq, dfChisq, lower = FALSE),
543 :     check.names = FALSE)
544 :     class(val) <- c("anova", class(val))
545 :     attr(val, "heading") <-
546 : bates 690 c(header, "Models:",
547 : bates 446 paste(names(mods),
548 :     unlist(lapply(lapply(calls, "[[", "formula"), deparse)),
549 : bates 690 sep = ": "))
550 : bates 446 return(val)
551 :     } else {
552 : bates 571 foo <- object
553 :     foo@status["factored"] <- FALSE
554 :     .Call("lmer_factor", foo, PACKAGE="Matrix")
555 :     dfr <- getFixDF(foo)
556 :     rcol <- ncol(foo@RXX)
557 :     ss <- foo@RXX[ , rcol]^2
558 :     ssr <- ss[[rcol]]
559 :     ss <- ss[seq(along = dfr)]
560 :     names(ss) <- object@cnames[[".fixed"]][seq(along = dfr)]
561 :     asgn <- foo@assign
562 :     terms <- foo@terms
563 :     nmeffects <- attr(terms, "term.labels")
564 :     if ("(Intercept)" %in% names(ss))
565 :     nmeffects <- c("(Intercept)", nmeffects)
566 :     ss <- unlist(lapply(split(ss, asgn), sum))
567 :     df <- unlist(lapply(split(asgn, asgn), length))
568 :     dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
569 :     ms <- ss/df
570 :     f <- ms/(ssr/dfr)
571 :     P <- pf(f, df, dfr, lower.tail = FALSE)
572 :     table <- data.frame(df, ss, ms, dfr, f, P)
573 :     dimnames(table) <-
574 :     list(nmeffects,
575 :     c("Df", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
576 :     if ("(Intercept)" %in% nmeffects) table <- table[-1,]
577 :     attr(table, "heading") <- "Analysis of Variance Table"
578 :     class(table) <- c("anova", "data.frame")
579 :     table
580 : bates 446 }
581 : bates 316 })
582 : bates 446
583 :     setMethod("update", signature(object = "lmer"),
584 :     function(object, formula., ..., evaluate = TRUE)
585 :     {
586 :     call <- object@call
587 :     if (is.null(call))
588 :     stop("need an object with call component")
589 :     extras <- match.call(expand.dots = FALSE)$...
590 :     if (!missing(formula.))
591 :     call$formula <- update.formula(formula(object), formula.)
592 :     if (length(extras) > 0) {
593 :     existing <- !is.na(match(names(extras), names(call)))
594 :     for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
595 :     if (any(!existing)) {
596 :     call <- c(as.list(call), extras[!existing])
597 :     call <- as.call(call)
598 :     }
599 :     }
600 :     if (evaluate)
601 :     eval(call, parent.frame())
602 :     else call
603 :     })
604 :    
605 :    
606 :     setMethod("confint", signature(object = "lmer"),
607 : maechler 832 function (object, parm, level = 0.95, ...)
608 : bates 446 {
609 :     cf <- fixef(object)
610 :     pnames <- names(cf)
611 : maechler 832 if (missing(parm))
612 : bates 446 parm <- seq(along = pnames)
613 : maechler 832 else if (is.character(parm))
614 : bates 446 parm <- match(parm, pnames, nomatch = 0)
615 :     a <- (1 - level)/2
616 :     a <- c(a, 1 - a)
617 :     pct <- paste(round(100 * a, 1), "%")
618 :     ci <- array(NA, dim = c(length(parm), 2),
619 :     dimnames = list(pnames[parm], pct))
620 :     ses <- sqrt(diag(vcov(object)))[parm]
621 : bates 449 ci[] <- cf[parm] + ses * t(outer(a, getFixDF(object)[parm], qt))
622 : bates 446 ci
623 :     })
624 :    
625 : bates 755 setMethod("deviance", "mer",
626 : bates 449 function(object, REML = NULL, ...) {
627 :     .Call("lmer_factor", object, PACKAGE = "Matrix")
628 :     if (is.null(REML))
629 : bates 755 REML <- object@method == "REML"
630 : bates 449 object@deviance[[ifelse(REML, "REML", "ML")]]
631 :     })
632 : bates 446
633 : deepayan 721
634 : bates 769 setMethod("deviance", "lmer",
635 :     function(object, ...) -2 * c(object@logLik))
636 : deepayan 721
637 : bates 769
638 : bates 449 setMethod("chol", signature(x = "lmer"),
639 :     function(x, pivot = FALSE, LINPACK = pivot) {
640 :     x@status["factored"] <- FALSE # force a decomposition
641 :     .Call("lmer_factor", x, PACKAGE = "Matrix")
642 :     })
643 :    
644 :     setMethod("solve", signature(a = "lmer", b = "missing"),
645 :     function(a, b, ...)
646 : bates 562 .Call("lmer_invert", a, PACKAGE = "Matrix")
647 : bates 449 )
648 :    
649 :     setMethod("formula", "lmer", function(x, ...) x@call$formula)
650 :    
651 :     setMethod("vcov", signature(object = "lmer"),
652 : bates 755 function(object, REML = object@method == "REML", useScale = TRUE,...) {
653 : bates 449 sc <- .Call("lmer_sigma", object, REML, PACKAGE = "Matrix")
654 :     rr <- object@RXX
655 :     nms <- object@cnames[[".fixed"]]
656 :     dimnames(rr) <- list(nms, nms)
657 :     nr <- nrow(rr)
658 :     rr <- rr[-nr, -nr, drop = FALSE]
659 :     rr <- rr %*% t(rr)
660 :     if (useScale) {
661 :     rr = sc^2 * rr
662 :     }
663 :     rr
664 :     })
665 :    
666 : maechler 832 ## Extract the L matrix
667 : bates 550 setAs("lmer", "dtTMatrix",
668 :     function(from)
669 :     {
670 :     ## force a refactorization if the factors have been inverted
671 :     if (from@status["inverted"]) from@status["factored"] <- FALSE
672 :     .Call("lmer_factor", from, PACKAGE = "Matrix")
673 :     L <- lapply(from@L, as, "dgTMatrix")
674 :     nf <- length(from@D)
675 :     Gp <- from@Gp
676 :     nL <- Gp[nf + 1]
677 : bates 562 Li <- integer(0)
678 :     Lj <- integer(0)
679 :     Lx <- double(0)
680 : bates 550 for (i in 1:nf) {
681 :     for (j in 1:i) {
682 :     Lij <- L[[Lind(i, j)]]
683 : bates 562 Li <- c(Li, Lij@i + Gp[i])
684 :     Lj <- c(Lj, Lij@j + Gp[j])
685 :     Lx <- c(Lx, Lij@x)
686 : bates 550 }
687 :     }
688 : bates 562 new("dtTMatrix", Dim = as.integer(c(nL, nL)), i = Li, j = Lj, x = Lx,
689 : bates 550 uplo = "L", diag = "U")
690 :     })
691 : bates 562
692 :     ## Extract the ZZX matrix
693 :     setAs("lmer", "dsTMatrix",
694 :     function(from)
695 :     {
696 :     .Call("lmer_inflate", from, PACKAGE = "Matrix")
697 :     ZZpO <- lapply(from@ZZpO, as, "dgTMatrix")
698 :     ZZ <- lapply(from@ZtZ, as, "dgTMatrix")
699 :     nf <- length(ZZpO)
700 :     Gp <- from@Gp
701 :     nZ <- Gp[nf + 1]
702 :     Zi <- integer(0)
703 :     Zj <- integer(0)
704 :     Zx <- double(0)
705 :     for (i in 1:nf) {
706 :     ZZpOi <- ZZpO[[i]]
707 :     Zi <- c(Zi, ZZpOi@i + Gp[i])
708 :     Zj <- c(Zj, ZZpOi@j + Gp[i])
709 :     Zx <- c(Zx, ZZpOi@x)
710 :     if (i > 1) {
711 :     for (j in 1:(i-1)) {
712 :     ZZij <- ZZ[[Lind(i, j)]]
713 :     ## off-diagonal blocks are transposed
714 :     Zi <- c(Zi, ZZij@j + Gp[j])
715 :     Zj <- c(Zj, ZZij@i + Gp[i])
716 :     Zx <- c(Zx, ZZij@x)
717 :     }
718 :     }
719 :     }
720 :     new("dsTMatrix", Dim = as.integer(c(nZ, nZ)), i = Zi, j = Zj, x = Zx,
721 :     uplo = "U")
722 :     })
723 : bates 689
724 :     setMethod("fitted", signature(object = "lmer"),
725 : bates 691 function(object, ...)
726 :     napredict(attr(object@frame, "na.action"), object@fitted))
727 : bates 689
728 :     setMethod("residuals", signature(object = "lmer"),
729 : bates 691 function(object, ...)
730 :     naresid(attr(object@frame, "na.action"), object@residuals))
731 : bates 689
732 :     setMethod("resid", signature(object = "lmer"),
733 :     function(object, ...) do.call("residuals", c(list(object), list(...))))
734 :    
735 :     setMethod("coef", signature(object = "lmer"),
736 :     function(object, ...)
737 :     {
738 : bates 769 fef <- data.frame(rbind(object@fixed), check.names = FALSE)
739 : bates 689 ref <- as(ranef(object), "list")
740 :     names(ref) <- names(object@flist)
741 :     val <- lapply(ref, function(x) fef[rep(1, nrow(x)),])
742 :     for (i in seq(a = val)) {
743 :     refi <- ref[[i]]
744 :     row.names(val[[i]]) <- row.names(refi)
745 :     if (!all(names(refi) %in% names(fef)))
746 :     stop("unable to align random and fixed effects")
747 :     val[[i]][ , names(refi)] <- val[[i]][ , names(refi)] + refi
748 :     }
749 :     new("lmer.coef", val)
750 :     })
751 :    
752 :     setMethod("plot", signature(x = "lmer.coef"),
753 :     function(x, y, ...)
754 :     {
755 : maechler 832 ## require("lattice", quietly = TRUE) -- now via Imports
756 :     varying <- unique(do.call("c",
757 :     lapply(x, function(el)
758 :     names(el)[sapply(el,
759 :     function(col)
760 :     any(col != col[1]))])))
761 :     gf <- do.call("rbind", lapply(x, "[", j = varying))
762 :     gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
763 :     switch(min(length(varying), 3),
764 :     qqmath(eval(substitute(~ x | .grp,
765 :     list(x = as.name(varying[1])))), gf, ...),
766 :     xyplot(eval(substitute(y ~ x | .grp,
767 :     list(y = as.name(varying[1]),
768 :     x = as.name(varying[2])))), gf, ...),
769 :     splom(~ gf | .grp, ...))
770 : bates 689 })
771 :    
772 :     setMethod("plot", signature(x = "lmer.ranef"),
773 :     function(x, y, ...)
774 :     {
775 : maechler 832 ## require("lattice", quietly = TRUE) -- now via Imports
776 :     lapply(x, function(x) {
777 :     cn <- lapply(colnames(x), as.name)
778 :     switch(min(ncol(x), 3),
779 :     qqmath(eval(substitute(~ x, list(x = cn[[1]]))), x, ...),
780 :     xyplot(eval(substitute(y ~ x,
781 :     list(y = cn[[1]],
782 :     x = cn[[2]]))), x, ...),
783 :     splom(~ x, ...))
784 :     })
785 : bates 689 })
786 :    
787 :     setMethod("with", signature(data = "lmer"),
788 : bates 690 function(data, expr, ...) {
789 : bates 691 dat <- eval(data@call$data)
790 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
791 :     dat <- dat[-na.act, ]
792 :     lst <- c(list(. = data), data@flist, data@frame, dat)
793 :     eval(substitute(expr), lst[unique(names(lst))])
794 :     })
795 : bates 690
796 : bates 691 setMethod("terms", signature(x = "lmer"),
797 :     function(x, ...) x@terms)
798 : bates 767
799 :     setMethod("show", signature(object="VarCorr"),
800 :     function(object)
801 :     {
802 :     digits <- max(3, getOption("digits") - 2)
803 :     useScale <- length(object@useScale) > 0 && object@useScale[1]
804 :     sc <- ifelse(useScale, object@scale, 1.)
805 :     reStdDev <- c(lapply(object@reSumry,
806 :     function(x, sc)
807 :     sc*x@stdDev,
808 :     sc = sc), list(Residual = sc))
809 :     reLens <- unlist(c(lapply(reStdDev, length)))
810 :     reMat <- array('', c(sum(reLens), 4),
811 :     list(rep('', sum(reLens)),
812 :     c("Groups", "Name", "Variance", "Std.Dev.")))
813 :     reMat[1+cumsum(reLens)-reLens, 1] <- names(reLens)
814 :     reMat[,2] <- c(unlist(lapply(reStdDev, names)), "")
815 :     reMat[,3] <- format(unlist(reStdDev)^2, digits = digits)
816 :     reMat[,4] <- format(unlist(reStdDev), digits = digits)
817 :     if (any(reLens > 1)) {
818 :     maxlen <- max(reLens)
819 :     corr <-
820 :     do.call("rbind",
821 :     lapply(object@reSumry,
822 :     function(x, maxlen) {
823 :     cc <- format(round(x, 3), nsmall = 3)
824 :     cc[!lower.tri(cc)] <- ""
825 :     nr <- dim(cc)[1]
826 :     if (nr >= maxlen) return(cc)
827 :     cbind(cc, matrix("", nr, maxlen-nr))
828 :     }, maxlen))
829 :     colnames(corr) <- c("Corr", rep("", maxlen - 1))
830 :     reMat <- cbind(reMat, rbind(corr, rep("", ncol(corr))))
831 :     }
832 :     if (!useScale) reMat <- reMat[-nrow(reMat),]
833 :     print(reMat, quote = FALSE)
834 :     })
835 : bates 769
836 : bates 879 setMethod("mcmcsamp", signature(object = "lmer"),
837 :     function(object, n = 1, verbose = FALSE, saveb = FALSE,
838 : bates 824 trans = TRUE, ...)
839 : bates 820 {
840 : bates 879 if (object@family$family == "gaussian" &&
841 :     object@family$link == "identity") {
842 : bates 861 glmer <- FALSE
843 : bates 879 ans <- .Call("lmer_MCMCsamp", object, saveb, n, trans,
844 : bates 820 PACKAGE = "Matrix")
845 :     } else {
846 : bates 861 glmer <- TRUE
847 :     if (trans)
848 : bates 864 warning("trans option not currently allowed for generalized models")
849 : bates 861 trans <- FALSE
850 : bates 820 ## Check arguments
851 : bates 879 if (length(object@Omega) > 1 || object@nc[1] > 1)
852 : bates 820 stop("mcmcsamp currently defined for glmm models with only one variance component")
853 :     cv <- Matrix:::lmerControl()
854 :     if (verbose) cv$msVerbose <- 1
855 : bates 879 family <- object@family
856 :     frm <- object@frame
857 : bates 810
858 : bates 820 ## recreate model matrices
859 : bates 879 fixed.form <- Matrix:::nobars(object@call$formula)
860 : bates 820 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
861 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
862 :     glm.fit <- glm(eval(fixed.form), family, frm, x = TRUE,
863 :     y = TRUE)
864 :     x <- glm.fit$x
865 :     y <- as.double(glm.fit$y)
866 : bates 879 bars <- Matrix:::findbars(object@call$formula[[3]])
867 : bates 820 random <-
868 :     lapply(bars,
869 :     function(x) list(model.matrix(eval(substitute(~term,
870 :     list(term=x[[2]]))),
871 :     frm),
872 :     eval(substitute(as.factor(fac)[,drop = TRUE],
873 :     list(fac = x[[3]])), frm)))
874 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
875 : bates 879 if (any(names(random) != names(object@flist)))
876 :     random <- random[names(object@flist)]
877 : bates 820 mmats <- c(lapply(random, "[[", 1),
878 :     .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
879 : bates 879 mer <- as(object, "mer")
880 : bates 781
881 : bates 820 ## establish the GS object and the ans matrix
882 : bates 879 eta <- glm.fit$linear.predictors # perhaps later change this to object@fitted?
883 : bates 820 wts <- glm.fit$prior.weights
884 :     wtssqr <- wts * wts
885 :     offset <- glm.fit$offset
886 :     if (is.null(offset)) offset <- numeric(length(eta))
887 :     off <- numeric(length(eta))
888 :     mu <- numeric(length(eta))
889 :     dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
890 :     linkinv <- quote(family$linkinv(eta))
891 :     mu.eta <- quote(family$mu.eta(eta))
892 :     variance <- quote(family$variance(mu))
893 :     LMEopt <- getAnywhere("LMEoptimize<-")
894 :     doLMEopt <- quote(LMEopt(x = mer, value = cv))
895 :     GSpt <- .Call("glmer_init", environment(), PACKAGE = "Matrix")
896 : bates 879 fixed <- object@fixed
897 : bates 820 varc <- .Call("lmer_coef", mer, 2, PACKAGE = "Matrix")
898 :     b <- .Call("lmer_ranef", mer, PACKAGE = "Matrix")
899 : bates 879 ans <- .Call("glmer_MCMCsamp", GSpt, b, fixed, varc, saveb, n,
900 : maechler 832 PACKAGE = "Matrix")
901 : bates 820 .Call("glmer_finalize", GSpt, PACKAGE = "Matrix");
902 :     }
903 : bates 879 gnms <- names(object@flist)
904 :     cnms <- object@cnames
905 :     ff <- fixef(object)
906 : bates 861 colnms <- c(names(ff), if (glmer) character(0) else "sigma^2",
907 : bates 842 unlist(lapply(seq(along = gnms),
908 :     function(i)
909 :     abbrvNms(gnms[i],cnms[[i]]))))
910 :     if (trans) {
911 :     ## parameter type: 0 => fixed effect, 1 => variance,
912 :     ## 2 => covariance
913 : bates 861 ptyp <- c(integer(length(ff)), if (glmer) integer(0) else 1:1,
914 : bates 842 unlist(lapply(seq(along = gnms),
915 :     function(i)
916 :     {
917 :     k <- length(cnms[[i]])
918 :     rep(1:2, c(k, (k*(k-1))/2))
919 :     })))
920 :     colnms[ptyp == 1] <-
921 :     paste("log(", colnms[ptyp == 1], ")", sep = "")
922 :     colnms[ptyp == 2] <-
923 :     paste("atanh(", colnms[ptyp == 2], ")", sep = "")
924 :     }
925 :     colnames(ans) <- colnms
926 : bates 820 ans
927 :     })
928 : bates 781
929 : bates 812 rWishart <- function(n, df, invScal)
930 :     .Call("Matrix_rWishart", n, df, invScal)
931 : bates 820
932 : bates 888
933 :     setMethod("model.matrix", signature(object = "lmer"),
934 :     function(object, ...)
935 : bates 878 {
936 : bates 879 frm <- object@frame
937 :     fixed.form <- Matrix:::nobars(object@call$formula)
938 : bates 878 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
939 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
940 : bates 888 glm.fit <- glm(eval(fixed.form), object@family, frm, x = TRUE, y = TRUE)
941 : bates 879 fxd <- unname(drop(glm.fit$x %*% fixef(object)))
942 : bates 888
943 :     ## Create the random effects model matrices
944 : bates 879 bars <- Matrix:::findbars(object@call$formula[[3]])
945 : bates 878 random <-
946 :     lapply(bars,
947 :     function(x) list(model.matrix(eval(substitute(~term,
948 :     list(term=x[[2]]))),
949 :     frm),
950 :     eval(substitute(as.factor(fac)[,drop = TRUE],
951 :     list(fac = x[[3]])), frm)))
952 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
953 :     ## re-order the random effects pairs if necessary
954 : bates 879 if (any(names(random) != names(object@flist)))
955 :     random <- random[names(object@flist)]
956 : bates 888 c(lapply(random, "[[", 1),
957 :     .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
958 :     })
959 :    
960 :     setMethod("simulate", signature(object = "lmer"),
961 :     function(object, nsim = 1,
962 :     seed = runif(1, 0, .Machine$integer.max),
963 :     ...)
964 :     {
965 :     runif(1) ## to initialize the RNG if necessary
966 :     RNGstate <- .Random.seed
967 :     set.seed(seed)
968 :    
969 :     family <- object@family
970 :     if (family$family != "gaussian" ||
971 :     family$link != "identity")
972 :     stop("simulation of generalized linear mixed models not yet implemented")
973 :    
974 :     ## pieces we will need later
975 :     scale <- .Call("lmer_sigma", object, object@method == "REML",
976 :     PACKAGE = "Matrix")
977 :     mmats <- model.matrix(object)
978 :     ff <- fixef(object)
979 :    
980 :     ###_FIXME: If the factor levels have been permuted, has the
981 :     ### permutation been applied in the stored frame? Otherwise we
982 :     ### need to check this.
983 :    
984 : bates 879 ## similate the linear predictors
985 : bates 888 lpred <- .Call("lmer_simulate", as(object, "mer"), nsim,
986 :     unname(drop(mmats[[length(mmats)]][,seq(a = ff)] %*% ff)),
987 :     mmats, TRUE, PACKAGE = "Matrix")
988 : bates 879 ## add per-observation noise term
989 : bates 888 lpred <- as.data.frame(lpred + rnorm(prod(dim(lpred)), sd = scale))
990 :    
991 :     ## save the seed and restore the RNG state
992 :     attr(lpred, "seed") <- seed
993 :     assign(".Random.seed", RNGstate, envir = .GlobalEnv)
994 :     lpred
995 : bates 878 })
996 : bates 879
997 :     simulate2 <- function(object, n = 1, ...)
998 :     {
999 :     family <- object@family
1000 :     if (family$family != "gaussian" ||
1001 :     family$link != "identity")
1002 :     stop("simulation of generalized linear mixed models not implemented yet")
1003 :    
1004 :     ## create the mean from the fixed effects
1005 :     frm <- object@frame
1006 :     fixed.form <- Matrix:::nobars(object@call$formula)
1007 :     if (inherits(fixed.form, "name")) # RHS is empty - use a constant
1008 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
1009 :     glm.fit <- glm(eval(fixed.form), family, frm, x = TRUE, y = TRUE)
1010 :     lpred <- matrix(glm.fit$x %*% fixef(object), nr = nrow(frm), nc = n)
1011 :    
1012 :     ## Create the random effects model matrices
1013 :     bars <- Matrix:::findbars(object@call$formula[[3]])
1014 :     random <-
1015 :     lapply(bars,
1016 :     function(x) list(model.matrix(eval(substitute(~term,
1017 :     list(term=x[[2]]))),
1018 :     frm),
1019 :     eval(substitute(as.factor(fac)[,drop = TRUE],
1020 :     list(fac = x[[3]])), frm)))
1021 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
1022 :     ## re-order the random effects pairs if necessary
1023 :     flist <- object@flist
1024 :     if (any(names(random) != names(flist)))
1025 :     random <- random[names(flist)]
1026 :     mmats <- lapply(random, "[[", 1)
1027 :    
1028 :     ## simulate the random effects
1029 :     scale <- .Call("lmer_sigma", object, object@method == "REML",
1030 :     PACKAGE = "Matrix")
1031 :     Omega <- object@Omega
1032 :     re <- lapply(seq(along = Omega),
1033 :     function(i) {
1034 :     om <- Omega[[i]]
1035 :     nr <- nrow(om)
1036 :     nlev <- length(levels(flist[[i]]))
1037 :     scale * array(solve(chol(new("dpoMatrix", Dim = dim(om),
1038 :     uplo = "U", x = c(om))),
1039 :     matrix(rnorm(nr * n * nlev),
1040 :     nr = nr))@x, c(nr, n, nlev))
1041 :     })
1042 :     ## apply the random effects
1043 :     for (j in seq(along = Omega)) {
1044 :     for (i in 1:nrow(lpred))
1045 :     lpred[i,] <- lpred[i,] + mmats[[j]][i,] %*% re[[j]][, , as.integer(flist[[j]])[i]]
1046 :     }
1047 :     ## add per-observation noise term
1048 :     lpred <- lpred + rnorm(prod(dim(lpred)), sd = scale)
1049 :     attr(lpred, "re") <- re
1050 :     lpred
1051 :     }
1052 :    
1053 :     refdist <- function(fm1, fm2, n, ...)
1054 :     {
1055 : bates 888 cv <- lmerControl()
1056 :     obs <- deviance(fm2) - deviance(fm1)
1057 : bates 879 newy <- simulate(fm2, n)
1058 : bates 888 mm1 <- model.matrix(fm1)
1059 :     mm2 <- model.matrix(fm2)
1060 : bates 879 ref <- numeric(n)
1061 : bates 888 mer1 <- as(fm1, "mer")
1062 :     mer2 <- as(fm2, "mer")
1063 : bates 879 for (j in 1:n) {
1064 : bates 888 .Call("lmer_update_y", mer2, newy[[j]], mm2, PACKAGE = "Matrix")
1065 :     LMEoptimize(mer2) <- cv
1066 :     .Call("lmer_update_y", mer1, newy[[j]], mm1, PACKAGE = "Matrix")
1067 :     LMEoptimize(mer1) <- cv
1068 :     ref[j] <- deviance(mer2) - deviance(mer1)
1069 : bates 879 }
1070 : bates 888 attr(ref, "observed") <- obs
1071 : bates 879 ref
1072 :     }

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge