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 777 - (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 :     if (is.call(term) && term[[1]] == as.name('|')) term[[1]] <- as.name('+')
55 :     term[[2]] <- subbars(term[[2]])
56 :     term[[3]] <- subbars(term[[3]])
57 :     term
58 :     }
59 :    
60 : bates 775 ## Control parameters for lmer
61 :     lmerControl <-
62 : bates 435 function(maxIter = 50,
63 : bates 769 msMaxIter = 200,
64 : bates 435 tolerance = sqrt((.Machine$double.eps)),
65 : bates 752 niterEM = 15,
66 : bates 435 msTol = sqrt(.Machine$double.eps),
67 :     msVerbose = getOption("verbose"),
68 : bates 769 PQLmaxIt = 30,
69 : bates 435 EMverbose = getOption("verbose"),
70 :     analyticGradient = TRUE,
71 : bates 775 analyticHessian = FALSE)
72 : bates 435 {
73 : bates 775 list(maxIter = as.integer(maxIter),
74 :     msMaxIter = as.integer(msMaxIter),
75 :     tolerance = as.double(tolerance),
76 :     niterEM = as.integer(niterEM),
77 :     msTol = as.double(msTol),
78 :     msVerbose = as.logical(msVerbose),
79 :     PQLmaxIt = as.integer(PQLmaxIt),
80 :     EMverbose = as.logical(EMverbose),
81 :     analyticGradient = as.logical(analyticGradient),
82 :     analyticHessian = as.logical(analyticHessian))
83 : bates 435 }
84 :    
85 : bates 755 setMethod("lmer", signature(formula = "formula"),
86 : bates 689 function(formula, data, family,
87 :     method = c("REML", "ML", "PQL", "Laplace", "AGQ"),
88 : bates 435 control = list(),
89 :     subset, weights, na.action, offset,
90 :     model = TRUE, x = FALSE, y = FALSE, ...)
91 : bates 755 { ## match and check parameters
92 :     if (length(formula) < 3) stop("formula must be a two-sided formula")
93 :     cv <- do.call("lmerControl", control)
94 :     if (lmm <- missing(family)) { # linear mixed model
95 :     method <- match.arg(method)
96 :     if (method %in% c("PQL", "Laplace", "AGQ")) {
97 :     warning(paste('Argument method = "', method,
98 :     '" is not meaningful for a linear mixed model.\n',
99 :     'Using method = "REML".\n', sep = ''))
100 :     method <- "REML"
101 :     }
102 :     } else { # generalized linear mixed model
103 :     method <- if (missing(method)) "PQL" else match.arg(method)
104 :     if (method == "ML") method <- "PQL"
105 :     if (method == "REML")
106 :     warning(paste('Argument method = "REML" is not meaningful',
107 :     'for a generalized linear mixed model.',
108 :     '\nUsing method = "PQL".\n'))
109 :     if (method %in% c("AGQ"))
110 :     stop("AGQ method not yet implemented")
111 : bates 704 }
112 :    
113 : bates 755 ## evaluate glm.fit, a generalized linear fit of fixed effects only
114 :     mf <- match.call()
115 :     m <- match(c("family", "data", "subset", "weights",
116 :     "na.action", "offset"), names(mf), 0)
117 :     mf <- mf[c(1, m)]
118 :     frame.form <- subbars(formula) # substitute `+' for `|'
119 :     fixed.form <- nobars(formula) # remove any terms with `|'
120 : bates 767 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
121 : bates 755 fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
122 :     environment(fixed.form) <- environment(frame.form) <- environment(formula)
123 :     mf$formula <- fixed.form
124 :     mf$x <- mf$model <- mf$y <- TRUE
125 :     mf[[1]] <- as.name("glm")
126 :     glm.fit <- eval(mf, parent.frame())
127 : bates 767 family <- glm.fit$family
128 :     x <- glm.fit$x
129 :     y <- as.double(glm.fit$y)
130 : bates 769 family <- glm.fit$family
131 : bates 449
132 : bates 755 ## evaluate a model frame for fixed and random effects
133 : bates 435 mf$formula <- frame.form
134 : bates 755 mf$x <- mf$model <- mf$y <- mf$family <- NULL
135 : bates 435 mf$drop.unused.levels <- TRUE
136 : bates 755 mf[[1]] <- as.name("model.frame")
137 : bates 435 frm <- eval(mf, parent.frame())
138 : bates 755
139 : bates 435 ## grouping factors and model matrices for random effects
140 :     bars <- findbars(formula[[3]])
141 :     random <-
142 :     lapply(bars,
143 :     function(x) list(model.matrix(eval(substitute(~term,
144 :     list(term=x[[2]]))),
145 :     frm),
146 : bates 452 eval(substitute(as.factor(fac)[,drop = TRUE],
147 : bates 435 list(fac = x[[3]])), frm)))
148 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
149 : bates 755
150 : bates 435 ## order factor list by decreasing number of levels
151 : bates 449 nlev <- sapply(random, function(x) length(levels(x[[2]])))
152 : bates 452 if (any(diff(nlev) > 0)) {
153 : bates 449 random <- random[rev(order(nlev))]
154 : bates 435 }
155 : bates 767
156 :     ## Create the model matrices and a mixed-effects representation (mer)
157 : bates 435 mmats <- c(lapply(random, "[[", 1),
158 : bates 755 .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
159 :     mer <- .Call("lmer_create", lapply(random, "[[", 2),
160 :     mmats, method, PACKAGE = "Matrix")
161 : bates 767 if (lmm) { ## linear mixed model
162 : bates 755 .Call("lmer_initial", mer, PACKAGE="Matrix")
163 :     .Call("lmer_ECMEsteps", mer, cv$niterEM, cv$EMverbose, PACKAGE = "Matrix")
164 :     LMEoptimize(mer) <- cv
165 :     fits <- .Call("lmer_fitted", mer, mmats, TRUE, PACKAGE = "Matrix")
166 : bates 767 return(new("lmer",
167 : bates 769 mer,
168 : bates 767 assign = attr(x, "assign"),
169 :     call = match.call(),
170 : bates 769 family = family, fitted = fits,
171 :     fixed = fixef(mer),
172 :     frame = if (model) frm else data.frame(),
173 :     logLik = logLik(mer),
174 : bates 755 residuals = unname(model.response(frm) - fits),
175 : bates 769 terms = glm.fit$terms))
176 : bates 755 }
177 :    
178 :     ## The rest of the function applies to generalized linear mixed models
179 :     gVerb <- getOption("verbose")
180 : bates 776 eta <- glm.fit$linear.predictors
181 : bates 767 wts <- glm.fit$prior.weights
182 : bates 774 wtssqr <- wts * wts
183 : bates 767 offset <- glm.fit$offset
184 :     if (is.null(offset)) offset <- numeric(length(eta))
185 : bates 776 off <- numeric(length(eta))
186 :     mu <- numeric(length(eta))
187 : bates 767
188 : bates 774 dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
189 : bates 767 linkinv <- quote(family$linkinv(eta))
190 :     mu.eta <- quote(family$mu.eta(eta))
191 :     variance <- quote(family$variance(mu))
192 : bates 775 LMEopt <- get("LMEoptimize<-")
193 :     doLMEopt <- quote(LMEopt(x = mer, value = cv))
194 : bates 767
195 : bates 775 GSpt <- .Call("glmer_init", environment())
196 :     .Call("glmer_PQL", GSpt) # obtain PQL estimates
197 : bates 755
198 : bates 774 fixInd <- seq(ncol(x))
199 :     ## pars[fixInd] == beta, pars[-fixInd] == theta
200 :     PQLpars <- c(fixef(mer),
201 :     .Call("lmer_coef", mer, 2, PACKAGE = "Matrix"))
202 : bates 775 ## set flag to skip fixed-effects in subsequent calls
203 :     mer@nc[length(mmats)] <- -mer@nc[length(mmats)]
204 : bates 777 ## indicator of constrained parameters
205 :     const <- c(rep(FALSE, length(fixInd)),
206 :     unlist(lapply(mer@nc[seq(along = random)],
207 :     function(k) 1:((k*(k+1))/2) <= k)
208 :     ))
209 : bates 776 devAGQ <- function(pars)
210 :     .Call("glmer_devAGQ", pars, GSpt, nAGQ, PACKAGE = "Matrix")
211 :    
212 : bates 777 nAGQ <- 1 # Laplacian approximation
213 :     loglik <- -devAGQ(PQLpars)/2
214 :     fxd <- PQLpars[fixInd]
215 : bates 775
216 : bates 777 if (method %in% c("Laplace", "AGQ")) {
217 :     if (exists("nlminb", mode = "function")) {
218 : bates 755 optimRes <-
219 : bates 777 nlminb(PQLpars, devAGQ,
220 : bates 755 lower = ifelse(const, 5e-10, -Inf),
221 :     control = list(trace = getOption("verbose"),
222 :     iter.max = cv$msMaxIter))
223 :     optpars <- optimRes$par
224 :     if (optimRes$convergence != 0)
225 :     warning("nlminb failed to converge")
226 : bates 776 loglik <- -optimRes$objective/2
227 : bates 755 } else {
228 :     optimRes <-
229 : bates 777 optim(PQLpars, devAGQ, method = "L-BFGS-B",
230 : bates 755 lower = ifelse(const, 5e-10, -Inf),
231 :     control = list(trace = getOption("verbose"),
232 : bates 776 maxit = cv$msMaxIter))
233 : bates 755 optpars <- optimRes$par
234 :     if (optimRes$convergence != 0)
235 :     warning("optim failed to converge")
236 : bates 776 loglik <- -optimRes$value
237 : bates 755 }
238 : bates 774 if (gVerb) {
239 : bates 772 cat(paste("convergence message", optimRes$message, "\n"))
240 : bates 777 }
241 :     fxd[] <- optpars[fixInd] ## preserve the names
242 : bates 755 }
243 :    
244 : bates 776 .Call("glmer_finalize", GSpt, PACKAGE = "Matrix")
245 :    
246 : bates 769 attributes(loglik) <- attributes(logLik(mer))
247 :     new("lmer", mer, frame = frm, terms = glm.fit$terms,
248 : bates 777 assign = attr(glm.fit$x, "assign"),
249 :     call = match.call(), family = family,
250 :     logLik = loglik, fixed = fxd)
251 : bates 435 })
252 :    
253 : bates 755 setReplaceMethod("LMEoptimize", signature(x="mer", value="list"),
254 : bates 316 function(x, value)
255 :     {
256 :     if (value$msMaxIter < 1) return(x)
257 :     nc <- x@nc
258 : bates 755 constr <- unlist(lapply(nc[1:(length(nc) - 2)],
259 :     function(k) 1:((k*(k+1))/2) <= k))
260 : bates 752 fn <- function(pars)
261 : bates 755 deviance(.Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix"))
262 :     gr <- NULL
263 :     if (value$analyticGradient)
264 :     gr <-
265 :     function(pars) {
266 :     if (!isTRUE(all.equal(pars,
267 :     .Call("lmer_coef", x,
268 :     2, PACKAGE = "Matrix"))))
269 :     .Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix")
270 :     .Call("lmer_gradient", x, 2, PACKAGE = "Matrix")
271 :     }
272 : bates 777 optimRes <-
273 :     if (exists("nlminb", mode = "function"))
274 :     nlminb(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
275 :     fn, gr,
276 :     lower = ifelse(constr, 5e-10, -Inf),
277 :     control = list(iter.max = value$msMaxIter,
278 :     trace = as.integer(value$msVerbose)))
279 :     else
280 :     optim(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
281 :     fn, gr, method = "L-BFGS-B",
282 :     lower = ifelse(constr, 5e-10, -Inf),
283 :     control = list(maxit = value$msMaxIter,
284 :     trace = as.integer(value$msVerbose)))
285 : bates 755 .Call("lmer_coefGets", x, optimRes$par, 2, PACKAGE = "Matrix")
286 : bates 316 if (optimRes$convergence != 0) {
287 : bates 777 warning(paste("optim or nlminb returned message",
288 :     optimRes$message,"\n"))
289 : bates 316 }
290 :     return(x)
291 :     })
292 :    
293 : bates 413 setMethod("ranef", signature(object = "lmer"),
294 : bates 689 function(object, accumulate = FALSE, ...) {
295 :     val <- new("lmer.ranef",
296 :     lapply(.Call("lmer_ranef", object, PACKAGE = "Matrix"),
297 :     data.frame, check.names = FALSE),
298 :     varFac = object@bVar,
299 :     stdErr = .Call("lmer_sigma", object,
300 : bates 755 object@method == "REML", PACKAGE = "Matrix"))
301 : bates 689 if (!accumulate || length(val@varFac) == 1) return(val)
302 :     ## check for nested factors
303 :     L <- object@L
304 :     if (any(sapply(seq(a = val), function(i) length(L[[Lind(i,i)]]@i))))
305 :     error("Require nested grouping factors to accumulate random effects")
306 :     val
307 : bates 316 })
308 :    
309 : bates 755 setMethod("fixef", signature(object = "mer"),
310 : bates 774 function(object, ...)
311 :     .Call("lmer_fixef", object, PACKAGE = "Matrix"))
312 : bates 316
313 : bates 769 setMethod("fixef", signature(object = "lmer"),
314 :     function(object, ...) object@fixed)
315 : deepayan 721
316 : bates 413 setMethod("VarCorr", signature(x = "lmer"),
317 : bates 316 function(x, REML = TRUE, useScale = TRUE, ...) {
318 : bates 550 val <- .Call("lmer_variances", x, PACKAGE = "Matrix")
319 : bates 316 for (i in seq(along = val)) {
320 :     dimnames(val[[i]]) = list(x@cnames[[i]], x@cnames[[i]])
321 :     val[[i]] = as(as(val[[i]], "pdmatrix"), "corrmatrix")
322 :     }
323 :     new("VarCorr",
324 : bates 449 scale = .Call("lmer_sigma", x, REML, PACKAGE = "Matrix"),
325 : bates 316 reSumry = val,
326 :     useScale = useScale)
327 :     })
328 :    
329 : bates 413 setMethod("gradient", signature(x = "lmer"),
330 : bates 755 function(x, unconst, ...)
331 :     .Call("lmer_gradient", x, unconst, PACKAGE = "Matrix"))
332 : bates 316
333 : bates 449 setMethod("summary", signature(object = "lmer"),
334 :     function(object, ...)
335 : bates 769 new("summary.lmer", object,
336 : bates 727 showCorrelation = TRUE,
337 : bates 769 useScale = !((object@family)$family %in% c("binomial", "poisson"))))
338 : bates 316
339 : bates 449 setMethod("show", signature(object = "lmer"),
340 :     function(object)
341 : bates 769 show(new("summary.lmer", object,
342 : bates 727 showCorrelation = FALSE,
343 : bates 769 useScale = !((object@family)$family %in% c("binomial", "poisson")))))
344 :    
345 : bates 449 setMethod("show", "summary.lmer",
346 : bates 316 function(object) {
347 : bates 727 fcoef <- object@fixed
348 : bates 449 useScale <- object@useScale
349 :     corF <- as(as(vcov(object, useScale = useScale), "pdmatrix"),
350 : bates 316 "corrmatrix")
351 :     DF <- getFixDF(object)
352 :     coefs <- cbind(fcoef, corF@stdDev, DF)
353 :     nc <- object@nc
354 :     dimnames(coefs) <-
355 :     list(names(fcoef), c("Estimate", "Std. Error", "DF"))
356 : bates 449 digits <- max(3, getOption("digits") - 2)
357 : bates 755 REML <- object@method == "REML"
358 : bates 727 llik <- object@logLik
359 : bates 449 dev <- object@deviance
360 :    
361 :     rdig <- 5
362 : bates 727 if (glz <- !(object@method %in% c("REML", "ML"))) {
363 :     cat(paste("Generalized linear mixed model fit using",
364 :     object@method, "\n"))
365 :     } else {
366 :     cat("Linear mixed-effects model fit by ")
367 : bates 755 cat(if(REML) "REML\n" else "maximum likelihood\n")
368 : bates 727 }
369 : bates 449 if (!is.null(object@call$formula)) {
370 :     cat("Formula:", deparse(object@call$formula),"\n")
371 :     }
372 :     if (!is.null(object@call$data)) {
373 :     cat(" Data:", deparse(object@call$data), "\n")
374 :     }
375 :     if (!is.null(object@call$subset)) {
376 :     cat(" Subset:",
377 :     deparse(asOneSidedFormula(object@call$subset)[[2]]),"\n")
378 :     }
379 : bates 727 if (glz) {
380 : bates 750 cat(" Family: ", object@family$family, "(",
381 :     object@family$link, " link)\n", sep = "")
382 : bates 727 print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
383 : bates 449 logLik = c(llik),
384 : bates 727 deviance = -2*llik,
385 :     row.names = ""))
386 :     } else {
387 :     print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
388 :     logLik = c(llik),
389 : bates 750 MLdeviance = dev["ML"],
390 : bates 449 REMLdeviance = dev["REML"],
391 :     row.names = ""))
392 : bates 727 }
393 : bates 449 cat("Random effects:\n")
394 : bates 777 show(VarCorr(object, useScale = useScale))
395 : bates 449 ngrps <- lapply(object@flist, function(x) length(levels(x)))
396 :     cat(sprintf("# of obs: %d, groups: ", object@nc[length(object@nc)]))
397 :     cat(paste(paste(names(ngrps), ngrps, sep = ", "), collapse = "; "))
398 :     cat("\n")
399 :     if (!useScale)
400 :     cat("\nEstimated scale (compare to 1) ",
401 : bates 755 .Call("lmer_sigma", object, FALSE, PACKAGE = "Matrix"),
402 : bates 449 "\n")
403 :     if (nrow(coefs) > 0) {
404 :     if (useScale) {
405 :     stat <- coefs[,1]/coefs[,2]
406 :     pval <- 2*pt(abs(stat), coefs[,3], lower = FALSE)
407 :     nms <- colnames(coefs)
408 :     coefs <- cbind(coefs, stat, pval)
409 :     colnames(coefs) <- c(nms, "t value", "Pr(>|t|)")
410 :     } else {
411 :     coefs <- coefs[, 1:2, drop = FALSE]
412 :     stat <- coefs[,1]/coefs[,2]
413 :     pval <- 2*pnorm(abs(stat), lower = FALSE)
414 :     nms <- colnames(coefs)
415 :     coefs <- cbind(coefs, stat, pval)
416 :     colnames(coefs) <- c(nms, "z value", "Pr(>|z|)")
417 :     }
418 :     cat("\nFixed effects:\n")
419 :     printCoefmat(coefs, tst.ind = 4, zap.ind = 3)
420 :     if (length(object@showCorrelation) > 0 && object@showCorrelation[1]) {
421 :     rn <- rownames(coefs)
422 :     dimnames(corF) <- list(
423 :     abbreviate(rn, minlen=11),
424 :     abbreviate(rn, minlen=6))
425 :     if (!is.null(corF)) {
426 :     p <- NCOL(corF)
427 :     if (p > 1) {
428 :     cat("\nCorrelation of Fixed Effects:\n")
429 :     corF <- format(round(corF, 3), nsmall = 3)
430 :     corF[!lower.tri(corF)] <- ""
431 :     print(corF[-1, -p, drop=FALSE], quote = FALSE)
432 :     }
433 :     }
434 :     }
435 :     }
436 :     invisible(object)
437 : bates 316 })
438 :    
439 : deepayan 707
440 : bates 689
441 :    
442 : bates 316 ## calculates degrees of freedom for fixed effects Wald tests
443 :     ## This is a placeholder. The answers are generally wrong. It will
444 :     ## be very tricky to decide what a 'right' answer should be with
445 :     ## crossed random effects.
446 :    
447 : bates 413 setMethod("getFixDF", signature(object="lmer"),
448 : bates 316 function(object, ...)
449 :     {
450 :     nc <- object@nc[-seq(along = object@Omega)]
451 : bates 777 p <- abs(nc[1]) - 1
452 : bates 316 n <- nc[2]
453 :     rep(n-p, p)
454 :     })
455 :    
456 : bates 755 setMethod("logLik", signature(object="mer"),
457 :     function(object, REML = object@method == "REML", ...) {
458 : bates 446 val <- -deviance(object, REML = REML)/2
459 :     nc <- object@nc[-seq(a = object@Omega)]
460 :     attr(val, "nall") <- attr(val, "nobs") <- nc[2]
461 : bates 755 attr(val, "df") <- nc[1] +
462 :     length(.Call("lmer_coef", object, 0, PACKAGE = "Matrix"))
463 : bates 446 attr(val, "REML") <- REML
464 :     class(val) <- "logLik"
465 :     val
466 :     })
467 :    
468 : bates 769 setMethod("logLik", signature(object="lmer"),
469 :     function(object, ...) object@logLik)
470 : deepayan 721
471 : bates 446 setMethod("anova", signature(object = "lmer"),
472 :     function(object, ...)
473 :     {
474 :     mCall <- match.call(expand.dots = TRUE)
475 :     dots <- list(...)
476 :     modp <- logical(0)
477 :     if (length(dots))
478 :     modp <- sapply(dots, inherits, "lmer") | sapply(dots, inherits, "lm")
479 :     if (any(modp)) { # multiple models - form table
480 :     opts <- dots[!modp]
481 :     mods <- c(list(object), dots[modp])
482 :     names(mods) <- sapply(as.list(mCall)[c(FALSE, TRUE, modp)], as.character)
483 :     mods <- mods[order(sapply(lapply(mods, logLik, REML = FALSE), attr, "df"))]
484 :     calls <- lapply(mods, slot, "call")
485 :     data <- lapply(calls, "[[", "data")
486 :     if (any(data != data[[1]])) stop("all models must be fit to the same data object")
487 :     header <- paste("Data:", data[[1]])
488 :     subset <- lapply(calls, "[[", "subset")
489 :     if (any(subset != subset[[1]])) stop("all models must use the same subset")
490 :     if (!is.null(subset[[1]]))
491 :     header <-
492 :     c(header, paste("Subset", deparse(subset[[1]]), sep = ": "))
493 :     llks <- lapply(mods, logLik, REML = FALSE)
494 :     Df <- sapply(llks, attr, "df")
495 :     llk <- unlist(llks)
496 :     chisq <- 2 * pmax(0, c(NA, diff(llk)))
497 :     dfChisq <- c(NA, diff(Df))
498 :     val <- data.frame(Df = Df,
499 :     AIC = sapply(llks, AIC),
500 :     BIC = sapply(llks, BIC),
501 :     logLik = llk,
502 :     "Chisq" = chisq,
503 :     "Chi Df" = dfChisq,
504 :     "Pr(>Chisq)" = pchisq(chisq, dfChisq, lower = FALSE),
505 :     check.names = FALSE)
506 :     class(val) <- c("anova", class(val))
507 :     attr(val, "heading") <-
508 : bates 690 c(header, "Models:",
509 : bates 446 paste(names(mods),
510 :     unlist(lapply(lapply(calls, "[[", "formula"), deparse)),
511 : bates 690 sep = ": "))
512 : bates 446 return(val)
513 :     } else {
514 : bates 571 foo <- object
515 :     foo@status["factored"] <- FALSE
516 :     .Call("lmer_factor", foo, PACKAGE="Matrix")
517 :     dfr <- getFixDF(foo)
518 :     rcol <- ncol(foo@RXX)
519 :     ss <- foo@RXX[ , rcol]^2
520 :     ssr <- ss[[rcol]]
521 :     ss <- ss[seq(along = dfr)]
522 :     names(ss) <- object@cnames[[".fixed"]][seq(along = dfr)]
523 :     asgn <- foo@assign
524 :     terms <- foo@terms
525 :     nmeffects <- attr(terms, "term.labels")
526 :     if ("(Intercept)" %in% names(ss))
527 :     nmeffects <- c("(Intercept)", nmeffects)
528 :     ss <- unlist(lapply(split(ss, asgn), sum))
529 :     df <- unlist(lapply(split(asgn, asgn), length))
530 :     dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
531 :     ms <- ss/df
532 :     f <- ms/(ssr/dfr)
533 :     P <- pf(f, df, dfr, lower.tail = FALSE)
534 :     table <- data.frame(df, ss, ms, dfr, f, P)
535 :     dimnames(table) <-
536 :     list(nmeffects,
537 :     c("Df", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
538 :     if ("(Intercept)" %in% nmeffects) table <- table[-1,]
539 :     attr(table, "heading") <- "Analysis of Variance Table"
540 :     class(table) <- c("anova", "data.frame")
541 :     table
542 : bates 446 }
543 : bates 316 })
544 : bates 446
545 :     setMethod("update", signature(object = "lmer"),
546 :     function(object, formula., ..., evaluate = TRUE)
547 :     {
548 :     call <- object@call
549 :     if (is.null(call))
550 :     stop("need an object with call component")
551 :     extras <- match.call(expand.dots = FALSE)$...
552 :     if (!missing(formula.))
553 :     call$formula <- update.formula(formula(object), formula.)
554 :     if (length(extras) > 0) {
555 :     existing <- !is.na(match(names(extras), names(call)))
556 :     for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
557 :     if (any(!existing)) {
558 :     call <- c(as.list(call), extras[!existing])
559 :     call <- as.call(call)
560 :     }
561 :     }
562 :     if (evaluate)
563 :     eval(call, parent.frame())
564 :     else call
565 :     })
566 :    
567 :    
568 :     setMethod("confint", signature(object = "lmer"),
569 :     function (object, parm, level = 0.95, ...)
570 :     {
571 :     cf <- fixef(object)
572 :     pnames <- names(cf)
573 :     if (missing(parm))
574 :     parm <- seq(along = pnames)
575 :     else if (is.character(parm))
576 :     parm <- match(parm, pnames, nomatch = 0)
577 :     a <- (1 - level)/2
578 :     a <- c(a, 1 - a)
579 :     pct <- paste(round(100 * a, 1), "%")
580 :     ci <- array(NA, dim = c(length(parm), 2),
581 :     dimnames = list(pnames[parm], pct))
582 :     ses <- sqrt(diag(vcov(object)))[parm]
583 : bates 449 ci[] <- cf[parm] + ses * t(outer(a, getFixDF(object)[parm], qt))
584 : bates 446 ci
585 :     })
586 :    
587 : bates 755 setMethod("deviance", "mer",
588 : bates 449 function(object, REML = NULL, ...) {
589 :     .Call("lmer_factor", object, PACKAGE = "Matrix")
590 :     if (is.null(REML))
591 : bates 755 REML <- object@method == "REML"
592 : bates 449 object@deviance[[ifelse(REML, "REML", "ML")]]
593 :     })
594 : bates 446
595 : deepayan 721
596 : bates 769 setMethod("deviance", "lmer",
597 :     function(object, ...) -2 * c(object@logLik))
598 : deepayan 721
599 : bates 769
600 : bates 449 setMethod("chol", signature(x = "lmer"),
601 :     function(x, pivot = FALSE, LINPACK = pivot) {
602 :     x@status["factored"] <- FALSE # force a decomposition
603 :     .Call("lmer_factor", x, PACKAGE = "Matrix")
604 :     })
605 :    
606 :     setMethod("solve", signature(a = "lmer", b = "missing"),
607 :     function(a, b, ...)
608 : bates 562 .Call("lmer_invert", a, PACKAGE = "Matrix")
609 : bates 449 )
610 :    
611 :     setMethod("formula", "lmer", function(x, ...) x@call$formula)
612 :    
613 :     setMethod("vcov", signature(object = "lmer"),
614 : bates 755 function(object, REML = object@method == "REML", useScale = TRUE,...) {
615 : bates 449 sc <- .Call("lmer_sigma", object, REML, PACKAGE = "Matrix")
616 :     rr <- object@RXX
617 :     nms <- object@cnames[[".fixed"]]
618 :     dimnames(rr) <- list(nms, nms)
619 :     nr <- nrow(rr)
620 :     rr <- rr[-nr, -nr, drop = FALSE]
621 :     rr <- rr %*% t(rr)
622 :     if (useScale) {
623 :     rr = sc^2 * rr
624 :     }
625 :     rr
626 :     })
627 :    
628 : bates 550 ## Extract the L matrix
629 :     setAs("lmer", "dtTMatrix",
630 :     function(from)
631 :     {
632 :     ## force a refactorization if the factors have been inverted
633 :     if (from@status["inverted"]) from@status["factored"] <- FALSE
634 :     .Call("lmer_factor", from, PACKAGE = "Matrix")
635 :     L <- lapply(from@L, as, "dgTMatrix")
636 :     nf <- length(from@D)
637 :     Gp <- from@Gp
638 :     nL <- Gp[nf + 1]
639 : bates 562 Li <- integer(0)
640 :     Lj <- integer(0)
641 :     Lx <- double(0)
642 : bates 550 for (i in 1:nf) {
643 :     for (j in 1:i) {
644 :     Lij <- L[[Lind(i, j)]]
645 : bates 562 Li <- c(Li, Lij@i + Gp[i])
646 :     Lj <- c(Lj, Lij@j + Gp[j])
647 :     Lx <- c(Lx, Lij@x)
648 : bates 550 }
649 :     }
650 : bates 562 new("dtTMatrix", Dim = as.integer(c(nL, nL)), i = Li, j = Lj, x = Lx,
651 : bates 550 uplo = "L", diag = "U")
652 :     })
653 : bates 562
654 :     ## Extract the ZZX matrix
655 :     setAs("lmer", "dsTMatrix",
656 :     function(from)
657 :     {
658 :     .Call("lmer_inflate", from, PACKAGE = "Matrix")
659 :     ZZpO <- lapply(from@ZZpO, as, "dgTMatrix")
660 :     ZZ <- lapply(from@ZtZ, as, "dgTMatrix")
661 :     nf <- length(ZZpO)
662 :     Gp <- from@Gp
663 :     nZ <- Gp[nf + 1]
664 :     Zi <- integer(0)
665 :     Zj <- integer(0)
666 :     Zx <- double(0)
667 :     for (i in 1:nf) {
668 :     ZZpOi <- ZZpO[[i]]
669 :     Zi <- c(Zi, ZZpOi@i + Gp[i])
670 :     Zj <- c(Zj, ZZpOi@j + Gp[i])
671 :     Zx <- c(Zx, ZZpOi@x)
672 :     if (i > 1) {
673 :     for (j in 1:(i-1)) {
674 :     ZZij <- ZZ[[Lind(i, j)]]
675 :     ## off-diagonal blocks are transposed
676 :     Zi <- c(Zi, ZZij@j + Gp[j])
677 :     Zj <- c(Zj, ZZij@i + Gp[i])
678 :     Zx <- c(Zx, ZZij@x)
679 :     }
680 :     }
681 :     }
682 :     new("dsTMatrix", Dim = as.integer(c(nZ, nZ)), i = Zi, j = Zj, x = Zx,
683 :     uplo = "U")
684 :     })
685 : bates 689
686 :     setMethod("fitted", signature(object = "lmer"),
687 : bates 691 function(object, ...)
688 :     napredict(attr(object@frame, "na.action"), object@fitted))
689 : bates 689
690 :     setMethod("residuals", signature(object = "lmer"),
691 : bates 691 function(object, ...)
692 :     naresid(attr(object@frame, "na.action"), object@residuals))
693 : bates 689
694 :     setMethod("resid", signature(object = "lmer"),
695 :     function(object, ...) do.call("residuals", c(list(object), list(...))))
696 :    
697 :     setMethod("coef", signature(object = "lmer"),
698 :     function(object, ...)
699 :     {
700 : bates 769 fef <- data.frame(rbind(object@fixed), check.names = FALSE)
701 : bates 689 ref <- as(ranef(object), "list")
702 :     names(ref) <- names(object@flist)
703 :     val <- lapply(ref, function(x) fef[rep(1, nrow(x)),])
704 :     for (i in seq(a = val)) {
705 :     refi <- ref[[i]]
706 :     row.names(val[[i]]) <- row.names(refi)
707 :     if (!all(names(refi) %in% names(fef)))
708 :     stop("unable to align random and fixed effects")
709 :     val[[i]][ , names(refi)] <- val[[i]][ , names(refi)] + refi
710 :     }
711 :     new("lmer.coef", val)
712 :     })
713 :    
714 :     setMethod("plot", signature(x = "lmer.coef"),
715 :     function(x, y, ...)
716 :     {
717 : bates 777 if (require("lattice", quietly = TRUE)) {
718 :     varying <- unique(do.call("c",
719 :     lapply(x, function(el)
720 :     names(el)[sapply(el,
721 :     function(col)
722 :     any(col != col[1]))])))
723 :     gf <- do.call("rbind", lapply(x, "[", j = varying))
724 :     gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
725 :     switch(min(length(varying), 3),
726 :     qqmath(eval(substitute(~ x | .grp,
727 :     list(x = as.name(varying[1])))), gf, ...),
728 :     xyplot(eval(substitute(y ~ x | .grp,
729 :     list(y = as.name(varying[1]),
730 :     x = as.name(varying[2])))), gf, ...),
731 :     splom(~ gf | .grp, ...))
732 :     }
733 : bates 689 })
734 :    
735 :     setMethod("plot", signature(x = "lmer.ranef"),
736 :     function(x, y, ...)
737 :     {
738 : bates 777 if (require("lattice", quietly = TRUE))
739 :     lapply(x, function(x) {
740 :     cn <- lapply(colnames(x), as.name)
741 :     switch(min(ncol(x), 3),
742 :     qqmath(eval(substitute(~ x,
743 :     list(x = cn[[1]]))),
744 :     x, ...),
745 :     xyplot(eval(substitute(y ~ x,
746 :     list(y = cn[[1]],
747 :     x = cn[[2]]))),
748 :     x, ...),
749 :     splom(~ x, ...))
750 :     })
751 : bates 689 })
752 :    
753 :     setMethod("with", signature(data = "lmer"),
754 : bates 690 function(data, expr, ...) {
755 : bates 691 dat <- eval(data@call$data)
756 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
757 :     dat <- dat[-na.act, ]
758 :     lst <- c(list(. = data), data@flist, data@frame, dat)
759 :     eval(substitute(expr), lst[unique(names(lst))])
760 :     })
761 : bates 690
762 : bates 691 setMethod("terms", signature(x = "lmer"),
763 :     function(x, ...) x@terms)
764 : bates 767
765 :     setMethod("show", signature(object="VarCorr"),
766 :     function(object)
767 :     {
768 :     digits <- max(3, getOption("digits") - 2)
769 :     useScale <- length(object@useScale) > 0 && object@useScale[1]
770 :     sc <- ifelse(useScale, object@scale, 1.)
771 :     reStdDev <- c(lapply(object@reSumry,
772 :     function(x, sc)
773 :     sc*x@stdDev,
774 :     sc = sc), list(Residual = sc))
775 :     reLens <- unlist(c(lapply(reStdDev, length)))
776 :     reMat <- array('', c(sum(reLens), 4),
777 :     list(rep('', sum(reLens)),
778 :     c("Groups", "Name", "Variance", "Std.Dev.")))
779 :     reMat[1+cumsum(reLens)-reLens, 1] <- names(reLens)
780 :     reMat[,2] <- c(unlist(lapply(reStdDev, names)), "")
781 :     reMat[,3] <- format(unlist(reStdDev)^2, digits = digits)
782 :     reMat[,4] <- format(unlist(reStdDev), digits = digits)
783 :     if (any(reLens > 1)) {
784 :     maxlen <- max(reLens)
785 :     corr <-
786 :     do.call("rbind",
787 :     lapply(object@reSumry,
788 :     function(x, maxlen) {
789 :     cc <- format(round(x, 3), nsmall = 3)
790 :     cc[!lower.tri(cc)] <- ""
791 :     nr <- dim(cc)[1]
792 :     if (nr >= maxlen) return(cc)
793 :     cbind(cc, matrix("", nr, maxlen-nr))
794 :     }, maxlen))
795 :     colnames(corr) <- c("Corr", rep("", maxlen - 1))
796 :     reMat <- cbind(reMat, rbind(corr, rep("", ncol(corr))))
797 :     }
798 :     if (!useScale) reMat <- reMat[-nrow(reMat),]
799 :     print(reMat, quote = FALSE)
800 :     })
801 : bates 769

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