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