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 774 - (view) (download)

1 : bates 767 # Methods for lmer and for the objects that it produces
2 : bates 689
3 :     ## Some utilities
4 :    
5 :     Lind <- function(i,j) {
6 :     if (i < j) stop(paste("Index i=", i,"must be >= index j=", j))
7 :     ((i - 1) * i)/2 + j
8 : bates 446 }
9 :    
10 : bates 769 # Return the pairs of expressions separated by vertical bars
11 : bates 689
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 :     # Return the formula omitting the pairs of expressions separated by vertical bars
23 :    
24 :     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 :     # Substitute the '+' function for the '|' function
46 :    
47 :     subbars <- function(term)
48 :     {
49 :     if (is.name(term) || is.numeric(term)) return(term)
50 :     if (length(term) == 2) {
51 :     term[[2]] <- subbars(term[[2]])
52 :     return(term)
53 :     }
54 :     stopifnot(length(term) == 3)
55 :     if (is.call(term) && term[[1]] == as.name('|')) term[[1]] <- as.name('+')
56 :     term[[2]] <- subbars(term[[2]])
57 :     term[[3]] <- subbars(term[[3]])
58 :     term
59 :     }
60 :    
61 : bates 435 lmerControl <- # Control parameters for lmer
62 :     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 :     analyticHessian=FALSE)
72 :     {
73 :     list(maxIter = maxIter,
74 :     msMaxIter = msMaxIter,
75 :     tolerance = tolerance,
76 :     niterEM = niterEM,
77 :     msTol = msTol,
78 :     msVerbose = msVerbose,
79 :     PQLmaxIt = PQLmaxIt,
80 :     EMverbose=EMverbose,
81 :     analyticHessian=analyticHessian,
82 :     analyticGradient=analyticGradient)
83 :     }
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 767 etaold <- eta <- glm.fit$linear.predictors
181 :     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 :    
186 : bates 774 dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
187 : bates 767 linkinv <- quote(family$linkinv(eta))
188 :     mu.eta <- quote(family$mu.eta(eta))
189 :     variance <- quote(family$variance(mu))
190 :    
191 : bates 755 mmo <- mmats
192 :     mmats[[1]][1,1] <- mmats[[1]][1,1]
193 :     conv <- FALSE
194 :     firstIter <- TRUE
195 :     msMaxIter.orig <- cv$msMaxIter
196 :    
197 :     for (iter in seq(length = cv$PQLmaxIt))
198 :     {
199 : bates 767 mu <- eval(linkinv) # family$linkinv(eta)
200 :     dmu.deta <- eval(mu.eta) # family$mu.eta(eta)
201 :     ## weights (note: wts is already square-rooted)
202 :     .Call("glmer_weight_matrix_list", mmo,
203 :     wts * dmu.deta / sqrt(eval(variance)), ## weights
204 :     eta - offset + (y - mu) / dmu.deta, ## working residual
205 :     mmats, PACKAGE="Matrix")
206 : bates 755 .Call("lmer_update_mm", mer, mmats, PACKAGE="Matrix")
207 :     if (firstIter) {
208 :     .Call("lmer_initial", mer, PACKAGE="Matrix")
209 :     if (gVerb) cat(" PQL iterations convergence criterion\n")
210 :     }
211 : bates 767 .Call("lmer_ECMEsteps", mer, cv$niterEM, cv$EMverbose,
212 :     PACKAGE = "Matrix")
213 : bates 755 LMEoptimize(mer) <- cv
214 : bates 767 eta <- offset + .Call("lmer_fitted", mer, mmo, TRUE,
215 :     PACKAGE = "Matrix")
216 : bates 755 crit <- max(abs(eta - etaold)) / (0.1 + max(abs(eta)))
217 :     if (gVerb) cat(sprintf("%03d: %#11g\n", as.integer(iter), crit))
218 :     ## use this to determine convergence
219 :     if (crit < cv$tolerance) {
220 :     conv <- TRUE
221 :     break
222 :     }
223 :     etaold[] <- eta
224 :     if (firstIter) { # Change the number of EM and optimization
225 :     cv$niterEM <- 2 # iterations for subsequent PQL iterations.
226 :     cv$msMaxIter <- 10
227 :     firstIter <- FALSE
228 :     }
229 :     }
230 :     if (!conv) warning("IRLS iterations for glmm did not converge")
231 :     cv$msMaxIter <- msMaxIter.orig
232 :    
233 : bates 774 fixInd <- seq(ncol(x))
234 :     ## pars[fixInd] == beta, pars[-fixInd] == theta
235 :     PQLpars <- c(fixef(mer),
236 :     .Call("lmer_coef", mer, 2, PACKAGE = "Matrix"))
237 : bates 767 env <- environment()
238 : bates 755
239 : bates 774 devLaplace <- function(pars)
240 :     .Call("lmer_devLaplace", pars, cv$tolerance, env, PACKAGE = "Matrix")
241 : bates 755
242 :     if (method == "Laplace") {
243 :     nc <- mer@nc
244 : bates 774 const <- c(rep(FALSE, length(fixInd)),
245 : bates 755 unlist(lapply(nc[1:(length(nc) - 2)],
246 :     function(k) 1:((k*(k+1))/2) <= k)))
247 : bates 774 ## set flag to skip fixed-effects in subsequent mer computations
248 :     mer@nc[length(mmats)] <- -mer@nc[length(mmats)]
249 : bates 755 RV <- lapply(R.Version()[c("major", "minor")], as.numeric)
250 :     if (RV$major == 2 && RV$minor >= 2.0) {
251 :     optimRes <-
252 : bates 774 nlminb(PQLpars, devLaplace,
253 : bates 755 lower = ifelse(const, 5e-10, -Inf),
254 :     control = list(trace = getOption("verbose"),
255 :     iter.max = cv$msMaxIter))
256 :     optpars <- optimRes$par
257 :     if (optimRes$convergence != 0)
258 :     warning("nlminb failed to converge")
259 :     } else {
260 :     optimRes <-
261 : bates 774 optim(PQLpars, devLaplace, method = "L-BFGS-B",
262 : bates 755 lower = ifelse(const, 5e-10, -Inf),
263 :     control = list(trace = getOption("verbose"),
264 :     reltol = cv$msTol, maxit = cv$msMaxIter))
265 :     optpars <- optimRes$par
266 :     if (optimRes$convergence != 0)
267 :     warning("optim failed to converge")
268 :     }
269 :    
270 : bates 774 if (gVerb) {
271 : bates 772 cat(paste("convergence message", optimRes$message, "\n"))
272 : bates 755 cat("Fixed effects:\n")
273 : bates 767 print(optimRes$par[fixInd])
274 :     cat("(box constrained) variance coefficients:\n")
275 :     print(optimRes$par[-fixInd])
276 : bates 774 }
277 :     loglik <- -optimRes$objective/2
278 :     fxd <- optpars[fixInd]
279 :     names(fxd) <- names(PQLpars)[fixInd]
280 :     ## reset flag to skip fixed-effects in mer computations
281 :     mer@nc[length(mmats)] <- -mer@nc[length(mmats)]
282 : bates 755 } else {
283 : bates 774 loglik <- -devLaplace(PQLpars)/2
284 :     fxd <- PQLpars[fixInd]
285 : bates 755 }
286 :    
287 : bates 769 attributes(loglik) <- attributes(logLik(mer))
288 :     new("lmer", mer, frame = frm, terms = glm.fit$terms,
289 :     assign = attr(glm.fit$x, "assign"), call = match.call(),
290 : bates 774 family = family, logLik = loglik, fixed = fxd)
291 : bates 435 })
292 :    
293 : bates 755 setReplaceMethod("LMEoptimize", signature(x="mer", value="list"),
294 : bates 316 function(x, value)
295 :     {
296 :     if (value$msMaxIter < 1) return(x)
297 :     nc <- x@nc
298 : bates 755 constr <- unlist(lapply(nc[1:(length(nc) - 2)],
299 :     function(k) 1:((k*(k+1))/2) <= k))
300 : bates 752 fn <- function(pars)
301 : bates 755 deviance(.Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix"))
302 :     gr <- NULL
303 :     if (value$analyticGradient)
304 :     gr <-
305 :     function(pars) {
306 :     if (!isTRUE(all.equal(pars,
307 :     .Call("lmer_coef", x,
308 :     2, PACKAGE = "Matrix"))))
309 :     .Call("lmer_coefGets", x, pars, 2, PACKAGE = "Matrix")
310 :     .Call("lmer_gradient", x, 2, PACKAGE = "Matrix")
311 :     }
312 : bates 752 RV <- lapply(R.Version()[c("major", "minor")], as.numeric)
313 : bates 755 if (RV$major == 2 && RV$minor >= 2.0) {
314 :     optimRes <- nlminb(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
315 : bates 752 fn, gr,
316 : bates 755 lower = ifelse(constr, 5e-10, -Inf),
317 : bates 752 control = list(iter.max = value$msMaxIter,
318 :     trace = as.integer(value$msVerbose)))
319 : bates 751 } else {
320 : bates 755 optimRes <- optim(.Call("lmer_coef", x, 2, PACKAGE = "Matrix"),
321 :     fn, gr, method = "L-BFGS-B",
322 :     lower = ifelse(constr, 5e-10, -Inf),
323 : bates 751 control = list(maxit = value$msMaxIter,
324 :     trace = as.integer(value$msVerbose)))
325 :     }
326 : bates 755 .Call("lmer_coefGets", x, optimRes$par, 2, PACKAGE = "Matrix")
327 : bates 316 if (optimRes$convergence != 0) {
328 :     warning(paste("optim returned message",optimRes$message,"\n"))
329 :     }
330 :     return(x)
331 :     })
332 :    
333 : bates 413 setMethod("ranef", signature(object = "lmer"),
334 : bates 689 function(object, accumulate = FALSE, ...) {
335 :     val <- new("lmer.ranef",
336 :     lapply(.Call("lmer_ranef", object, PACKAGE = "Matrix"),
337 :     data.frame, check.names = FALSE),
338 :     varFac = object@bVar,
339 :     stdErr = .Call("lmer_sigma", object,
340 : bates 755 object@method == "REML", PACKAGE = "Matrix"))
341 : bates 689 if (!accumulate || length(val@varFac) == 1) return(val)
342 :     ## check for nested factors
343 :     L <- object@L
344 :     if (any(sapply(seq(a = val), function(i) length(L[[Lind(i,i)]]@i))))
345 :     error("Require nested grouping factors to accumulate random effects")
346 :     val
347 : bates 316 })
348 :    
349 : bates 755 setMethod("fixef", signature(object = "mer"),
350 : bates 774 function(object, ...)
351 :     .Call("lmer_fixef", object, PACKAGE = "Matrix"))
352 : bates 316
353 : bates 774
354 : bates 769 setMethod("fixef", signature(object = "lmer"),
355 :     function(object, ...) object@fixed)
356 : deepayan 721
357 : bates 413 setMethod("VarCorr", signature(x = "lmer"),
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 :    
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 :    
402 :     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 :     show(VarCorr(object))
436 :     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 : deepayan 707
481 : bates 689
482 :    
483 : bates 316 ## calculates degrees of freedom for fixed effects Wald tests
484 :     ## This is a placeholder. The answers are generally wrong. It will
485 :     ## be very tricky to decide what a 'right' answer should be with
486 :     ## crossed random effects.
487 :    
488 : bates 413 setMethod("getFixDF", signature(object="lmer"),
489 : bates 316 function(object, ...)
490 :     {
491 :     nc <- object@nc[-seq(along = object@Omega)]
492 :     p <- nc[1] - 1
493 :     n <- nc[2]
494 :     rep(n-p, p)
495 :     })
496 :    
497 : bates 755 setMethod("logLik", signature(object="mer"),
498 :     function(object, REML = object@method == "REML", ...) {
499 : bates 446 val <- -deviance(object, REML = REML)/2
500 :     nc <- object@nc[-seq(a = object@Omega)]
501 :     attr(val, "nall") <- attr(val, "nobs") <- nc[2]
502 : bates 755 attr(val, "df") <- nc[1] +
503 :     length(.Call("lmer_coef", object, 0, PACKAGE = "Matrix"))
504 : bates 446 attr(val, "REML") <- REML
505 :     class(val) <- "logLik"
506 :     val
507 :     })
508 :    
509 : bates 769 setMethod("logLik", signature(object="lmer"),
510 :     function(object, ...) object@logLik)
511 : deepayan 721
512 : bates 446 setMethod("anova", signature(object = "lmer"),
513 :     function(object, ...)
514 :     {
515 :     mCall <- match.call(expand.dots = TRUE)
516 :     dots <- list(...)
517 :     modp <- logical(0)
518 :     if (length(dots))
519 :     modp <- sapply(dots, inherits, "lmer") | sapply(dots, inherits, "lm")
520 :     if (any(modp)) { # multiple models - form table
521 :     opts <- dots[!modp]
522 :     mods <- c(list(object), dots[modp])
523 :     names(mods) <- sapply(as.list(mCall)[c(FALSE, TRUE, modp)], as.character)
524 :     mods <- mods[order(sapply(lapply(mods, logLik, REML = FALSE), attr, "df"))]
525 :     calls <- lapply(mods, slot, "call")
526 :     data <- lapply(calls, "[[", "data")
527 :     if (any(data != data[[1]])) stop("all models must be fit to the same data object")
528 :     header <- paste("Data:", data[[1]])
529 :     subset <- lapply(calls, "[[", "subset")
530 :     if (any(subset != subset[[1]])) stop("all models must use the same subset")
531 :     if (!is.null(subset[[1]]))
532 :     header <-
533 :     c(header, paste("Subset", deparse(subset[[1]]), sep = ": "))
534 :     llks <- lapply(mods, logLik, REML = FALSE)
535 :     Df <- sapply(llks, attr, "df")
536 :     llk <- unlist(llks)
537 :     chisq <- 2 * pmax(0, c(NA, diff(llk)))
538 :     dfChisq <- c(NA, diff(Df))
539 :     val <- data.frame(Df = Df,
540 :     AIC = sapply(llks, AIC),
541 :     BIC = sapply(llks, BIC),
542 :     logLik = llk,
543 :     "Chisq" = chisq,
544 :     "Chi Df" = dfChisq,
545 :     "Pr(>Chisq)" = pchisq(chisq, dfChisq, lower = FALSE),
546 :     check.names = FALSE)
547 :     class(val) <- c("anova", class(val))
548 :     attr(val, "heading") <-
549 : bates 690 c(header, "Models:",
550 : bates 446 paste(names(mods),
551 :     unlist(lapply(lapply(calls, "[[", "formula"), deparse)),
552 : bates 690 sep = ": "))
553 : bates 446 return(val)
554 :     } else {
555 : bates 571 foo <- object
556 :     foo@status["factored"] <- FALSE
557 :     .Call("lmer_factor", foo, PACKAGE="Matrix")
558 :     dfr <- getFixDF(foo)
559 :     rcol <- ncol(foo@RXX)
560 :     ss <- foo@RXX[ , rcol]^2
561 :     ssr <- ss[[rcol]]
562 :     ss <- ss[seq(along = dfr)]
563 :     names(ss) <- object@cnames[[".fixed"]][seq(along = dfr)]
564 :     asgn <- foo@assign
565 :     terms <- foo@terms
566 :     nmeffects <- attr(terms, "term.labels")
567 :     if ("(Intercept)" %in% names(ss))
568 :     nmeffects <- c("(Intercept)", nmeffects)
569 :     ss <- unlist(lapply(split(ss, asgn), sum))
570 :     df <- unlist(lapply(split(asgn, asgn), length))
571 :     dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
572 :     ms <- ss/df
573 :     f <- ms/(ssr/dfr)
574 :     P <- pf(f, df, dfr, lower.tail = FALSE)
575 :     table <- data.frame(df, ss, ms, dfr, f, P)
576 :     dimnames(table) <-
577 :     list(nmeffects,
578 :     c("Df", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
579 :     if ("(Intercept)" %in% nmeffects) table <- table[-1,]
580 :     attr(table, "heading") <- "Analysis of Variance Table"
581 :     class(table) <- c("anova", "data.frame")
582 :     table
583 : bates 446 }
584 : bates 316 })
585 : bates 446
586 :     setMethod("update", signature(object = "lmer"),
587 :     function(object, formula., ..., evaluate = TRUE)
588 :     {
589 :     call <- object@call
590 :     if (is.null(call))
591 :     stop("need an object with call component")
592 :     extras <- match.call(expand.dots = FALSE)$...
593 :     if (!missing(formula.))
594 :     call$formula <- update.formula(formula(object), formula.)
595 :     if (length(extras) > 0) {
596 :     existing <- !is.na(match(names(extras), names(call)))
597 :     for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
598 :     if (any(!existing)) {
599 :     call <- c(as.list(call), extras[!existing])
600 :     call <- as.call(call)
601 :     }
602 :     }
603 :     if (evaluate)
604 :     eval(call, parent.frame())
605 :     else call
606 :     })
607 :    
608 :    
609 :     setMethod("confint", signature(object = "lmer"),
610 :     function (object, parm, level = 0.95, ...)
611 :     {
612 :     cf <- fixef(object)
613 :     pnames <- names(cf)
614 :     if (missing(parm))
615 :     parm <- seq(along = pnames)
616 :     else if (is.character(parm))
617 :     parm <- match(parm, pnames, nomatch = 0)
618 :     a <- (1 - level)/2
619 :     a <- c(a, 1 - a)
620 :     pct <- paste(round(100 * a, 1), "%")
621 :     ci <- array(NA, dim = c(length(parm), 2),
622 :     dimnames = list(pnames[parm], pct))
623 :     ses <- sqrt(diag(vcov(object)))[parm]
624 : bates 449 ci[] <- cf[parm] + ses * t(outer(a, getFixDF(object)[parm], qt))
625 : bates 446 ci
626 :     })
627 :    
628 : bates 769 ##setMethod("param", signature(object = "lmer"),
629 :     ## function(object, unconst = FALSE, ...) {
630 :     ## .Call("lmer_coef", object, unconst, PACKAGE = "Matrix")
631 :     ## })
632 : bates 446
633 : bates 755 setMethod("deviance", "mer",
634 : bates 449 function(object, REML = NULL, ...) {
635 :     .Call("lmer_factor", object, PACKAGE = "Matrix")
636 :     if (is.null(REML))
637 : bates 755 REML <- object@method == "REML"
638 : bates 449 object@deviance[[ifelse(REML, "REML", "ML")]]
639 :     })
640 : bates 446
641 : deepayan 721
642 : bates 769 setMethod("deviance", "lmer",
643 :     function(object, ...) -2 * c(object@logLik))
644 : deepayan 721
645 : bates 769
646 : bates 449 setMethod("chol", signature(x = "lmer"),
647 :     function(x, pivot = FALSE, LINPACK = pivot) {
648 :     x@status["factored"] <- FALSE # force a decomposition
649 :     .Call("lmer_factor", x, PACKAGE = "Matrix")
650 :     })
651 :    
652 :     setMethod("solve", signature(a = "lmer", b = "missing"),
653 :     function(a, b, ...)
654 : bates 562 .Call("lmer_invert", a, PACKAGE = "Matrix")
655 : bates 449 )
656 :    
657 :     setMethod("formula", "lmer", function(x, ...) x@call$formula)
658 :    
659 :     setMethod("vcov", signature(object = "lmer"),
660 : bates 755 function(object, REML = object@method == "REML", useScale = TRUE,...) {
661 : bates 449 sc <- .Call("lmer_sigma", object, REML, PACKAGE = "Matrix")
662 :     rr <- object@RXX
663 :     nms <- object@cnames[[".fixed"]]
664 :     dimnames(rr) <- list(nms, nms)
665 :     nr <- nrow(rr)
666 :     rr <- rr[-nr, -nr, drop = FALSE]
667 :     rr <- rr %*% t(rr)
668 :     if (useScale) {
669 :     rr = sc^2 * rr
670 :     }
671 :     rr
672 :     })
673 :    
674 : bates 550 ## Extract the L matrix
675 :     setAs("lmer", "dtTMatrix",
676 :     function(from)
677 :     {
678 :     ## force a refactorization if the factors have been inverted
679 :     if (from@status["inverted"]) from@status["factored"] <- FALSE
680 :     .Call("lmer_factor", from, PACKAGE = "Matrix")
681 :     L <- lapply(from@L, as, "dgTMatrix")
682 :     nf <- length(from@D)
683 :     Gp <- from@Gp
684 :     nL <- Gp[nf + 1]
685 : bates 562 Li <- integer(0)
686 :     Lj <- integer(0)
687 :     Lx <- double(0)
688 : bates 550 for (i in 1:nf) {
689 :     for (j in 1:i) {
690 :     Lij <- L[[Lind(i, j)]]
691 : bates 562 Li <- c(Li, Lij@i + Gp[i])
692 :     Lj <- c(Lj, Lij@j + Gp[j])
693 :     Lx <- c(Lx, Lij@x)
694 : bates 550 }
695 :     }
696 : bates 562 new("dtTMatrix", Dim = as.integer(c(nL, nL)), i = Li, j = Lj, x = Lx,
697 : bates 550 uplo = "L", diag = "U")
698 :     })
699 : bates 562
700 :     ## Extract the ZZX matrix
701 :     setAs("lmer", "dsTMatrix",
702 :     function(from)
703 :     {
704 :     .Call("lmer_inflate", from, PACKAGE = "Matrix")
705 :     ZZpO <- lapply(from@ZZpO, as, "dgTMatrix")
706 :     ZZ <- lapply(from@ZtZ, as, "dgTMatrix")
707 :     nf <- length(ZZpO)
708 :     Gp <- from@Gp
709 :     nZ <- Gp[nf + 1]
710 :     Zi <- integer(0)
711 :     Zj <- integer(0)
712 :     Zx <- double(0)
713 :     for (i in 1:nf) {
714 :     ZZpOi <- ZZpO[[i]]
715 :     Zi <- c(Zi, ZZpOi@i + Gp[i])
716 :     Zj <- c(Zj, ZZpOi@j + Gp[i])
717 :     Zx <- c(Zx, ZZpOi@x)
718 :     if (i > 1) {
719 :     for (j in 1:(i-1)) {
720 :     ZZij <- ZZ[[Lind(i, j)]]
721 :     ## off-diagonal blocks are transposed
722 :     Zi <- c(Zi, ZZij@j + Gp[j])
723 :     Zj <- c(Zj, ZZij@i + Gp[i])
724 :     Zx <- c(Zx, ZZij@x)
725 :     }
726 :     }
727 :     }
728 :     new("dsTMatrix", Dim = as.integer(c(nZ, nZ)), i = Zi, j = Zj, x = Zx,
729 :     uplo = "U")
730 :     })
731 : bates 689
732 :     setMethod("fitted", signature(object = "lmer"),
733 : bates 691 function(object, ...)
734 :     napredict(attr(object@frame, "na.action"), object@fitted))
735 : bates 689
736 :     setMethod("residuals", signature(object = "lmer"),
737 : bates 691 function(object, ...)
738 :     naresid(attr(object@frame, "na.action"), object@residuals))
739 : bates 689
740 :     setMethod("resid", signature(object = "lmer"),
741 :     function(object, ...) do.call("residuals", c(list(object), list(...))))
742 :    
743 :     setMethod("coef", signature(object = "lmer"),
744 :     function(object, ...)
745 :     {
746 : bates 769 fef <- data.frame(rbind(object@fixed), check.names = FALSE)
747 : bates 689 ref <- as(ranef(object), "list")
748 :     names(ref) <- names(object@flist)
749 :     val <- lapply(ref, function(x) fef[rep(1, nrow(x)),])
750 :     for (i in seq(a = val)) {
751 :     refi <- ref[[i]]
752 :     row.names(val[[i]]) <- row.names(refi)
753 :     if (!all(names(refi) %in% names(fef)))
754 :     stop("unable to align random and fixed effects")
755 :     val[[i]][ , names(refi)] <- val[[i]][ , names(refi)] + refi
756 :     }
757 :     new("lmer.coef", val)
758 :     })
759 :    
760 :     setMethod("plot", signature(x = "lmer.coef"),
761 :     function(x, y, ...)
762 :     {
763 :     varying <- unique(do.call("c",
764 :     lapply(x, function(el)
765 :     names(el)[sapply(el,
766 :     function(col)
767 :     any(col != col[1]))])))
768 :     gf <- do.call("rbind", lapply(x, "[", j = varying))
769 :     gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
770 :     switch(min(length(varying), 3),
771 :     qqmath(eval(substitute(~ x | .grp,
772 :     list(x = as.name(varying[1])))), gf, ...),
773 :     xyplot(eval(substitute(y ~ x | .grp,
774 :     list(y = as.name(varying[1]),
775 :     x = as.name(varying[2])))), gf, ...),
776 :     splom(~ gf | .grp, ...))
777 :     })
778 :    
779 :     setMethod("plot", signature(x = "lmer.ranef"),
780 :     function(x, y, ...)
781 :     {
782 :     lapply(x, function(x) {
783 :     cn <- lapply(colnames(x), as.name)
784 :     switch(min(ncol(x), 3),
785 :     qqmath(eval(substitute(~ x, list(x = cn[[1]]))), x, ...),
786 :     xyplot(eval(substitute(y ~ x, list(y = cn[[1]], x = cn[[2]]))),
787 :     x, ...),
788 :     splom(~ x, ...))
789 :     })
790 :     })
791 :    
792 :     setMethod("with", signature(data = "lmer"),
793 : bates 690 function(data, expr, ...) {
794 : bates 691 dat <- eval(data@call$data)
795 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
796 :     dat <- dat[-na.act, ]
797 :     lst <- c(list(. = data), data@flist, data@frame, dat)
798 :     eval(substitute(expr), lst[unique(names(lst))])
799 :     })
800 : bates 690
801 : bates 691 setMethod("terms", signature(x = "lmer"),
802 :     function(x, ...) x@terms)
803 : bates 767
804 :     setMethod("show", signature(object="VarCorr"),
805 :     function(object)
806 :     {
807 :     digits <- max(3, getOption("digits") - 2)
808 :     useScale <- length(object@useScale) > 0 && object@useScale[1]
809 :     sc <- ifelse(useScale, object@scale, 1.)
810 :     reStdDev <- c(lapply(object@reSumry,
811 :     function(x, sc)
812 :     sc*x@stdDev,
813 :     sc = sc), list(Residual = sc))
814 :     reLens <- unlist(c(lapply(reStdDev, length)))
815 :     reMat <- array('', c(sum(reLens), 4),
816 :     list(rep('', sum(reLens)),
817 :     c("Groups", "Name", "Variance", "Std.Dev.")))
818 :     reMat[1+cumsum(reLens)-reLens, 1] <- names(reLens)
819 :     reMat[,2] <- c(unlist(lapply(reStdDev, names)), "")
820 :     reMat[,3] <- format(unlist(reStdDev)^2, digits = digits)
821 :     reMat[,4] <- format(unlist(reStdDev), digits = digits)
822 :     if (any(reLens > 1)) {
823 :     maxlen <- max(reLens)
824 :     corr <-
825 :     do.call("rbind",
826 :     lapply(object@reSumry,
827 :     function(x, maxlen) {
828 :     cc <- format(round(x, 3), nsmall = 3)
829 :     cc[!lower.tri(cc)] <- ""
830 :     nr <- dim(cc)[1]
831 :     if (nr >= maxlen) return(cc)
832 :     cbind(cc, matrix("", nr, maxlen-nr))
833 :     }, maxlen))
834 :     colnames(corr) <- c("Corr", rep("", maxlen - 1))
835 :     reMat <- cbind(reMat, rbind(corr, rep("", ncol(corr))))
836 :     }
837 :     if (!useScale) reMat <- reMat[-nrow(reMat),]
838 :     print(reMat, quote = FALSE)
839 :     })
840 : 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