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 752 - (view) (download)
Original Path: branches/trunk-lme4/R/lmer.R

1 : bates 689 ## Methods for lmer and for the objects that it produces
2 :    
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 689 Dhalf <- function(from) {
11 :     D <- from@D
12 :     nf <- length(D)
13 :     Gp <- from@Gp
14 :     res <- array(0, rep(Gp[nf+1],2))
15 :     for (i in 1:nf) {
16 :     DD <- D[[i]]
17 :     dd <- dim(DD)
18 :     for (k in 1:dd[3]) {
19 :     mm <- array(DD[ , , k], dd[1:2])
20 :     base <- Gp[i] + (k - 1)*dd[1]
21 :     res[cbind(c(base + row(mm)), c(base + col(mm)))] <- c(mm)
22 :     }
23 :     }
24 :     res
25 :     }
26 :    
27 : bates 435 lmerControl <- # Control parameters for lmer
28 :     function(maxIter = 50,
29 :     msMaxIter = 50,
30 :     tolerance = sqrt((.Machine$double.eps)),
31 : bates 752 niterEM = 15,
32 : bates 435 msTol = sqrt(.Machine$double.eps),
33 :     msVerbose = getOption("verbose"),
34 :     PQLmaxIt = 20,
35 :     EMverbose = getOption("verbose"),
36 :     analyticGradient = TRUE,
37 :     analyticHessian=FALSE)
38 :     {
39 :     list(maxIter = maxIter,
40 :     msMaxIter = msMaxIter,
41 :     tolerance = tolerance,
42 :     niterEM = niterEM,
43 :     msTol = msTol,
44 :     msVerbose = msVerbose,
45 :     PQLmaxIt = PQLmaxIt,
46 :     EMverbose=EMverbose,
47 :     analyticHessian=analyticHessian,
48 :     analyticGradient=analyticGradient)
49 :     }
50 :    
51 : bates 689 setMethod("lmer", signature(formula = "formula", family = "missing"),
52 :     function(formula, data, family,
53 :     method = c("REML", "ML", "PQL", "Laplace", "AGQ"),
54 : bates 435 control = list(),
55 :     subset, weights, na.action, offset,
56 :     model = TRUE, x = FALSE, y = FALSE, ...)
57 :     {
58 :     # match and check parameters
59 : bates 704 method <- match.arg(method)
60 :     if (method %in% c("PQL", "Laplace", "AGQ")) {
61 :     warning(paste('Argument method = "', method,
62 :     '" is not meaningful for a linear mixed model.\n',
63 :     'Using method = "REML".\n', sep = ''))
64 :     method <- "REML"
65 :     }
66 : bates 435 controlvals <- do.call("lmerControl", control)
67 : bates 704 controlvals$REML <- REML <- method == "REML"
68 :    
69 : bates 435 if (length(formula) < 3) stop("formula must be a two-sided formula")
70 : bates 449
71 :     mf <- match.call() # create the model frame as frm
72 : bates 435 m <- match(c("data", "subset", "weights", "na.action", "offset"),
73 :     names(mf), 0)
74 :     mf <- mf[c(1, m)]
75 :     mf[[1]] <- as.name("model.frame")
76 :     frame.form <- subbars(formula)
77 :     environment(frame.form) <- environment(formula)
78 :     mf$formula <- frame.form
79 :     mf$drop.unused.levels <- TRUE
80 :     frm <- eval(mf, parent.frame())
81 : bates 449
82 : bates 435 ## grouping factors and model matrices for random effects
83 :     bars <- findbars(formula[[3]])
84 :     random <-
85 :     lapply(bars,
86 :     function(x) list(model.matrix(eval(substitute(~term,
87 :     list(term=x[[2]]))),
88 :     frm),
89 : bates 452 eval(substitute(as.factor(fac)[,drop = TRUE],
90 : bates 435 list(fac = x[[3]])), frm)))
91 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
92 : bates 449
93 : bates 435 ## order factor list by decreasing number of levels
94 : bates 449 nlev <- sapply(random, function(x) length(levels(x[[2]])))
95 : bates 452 if (any(diff(nlev) > 0)) {
96 : bates 449 random <- random[rev(order(nlev))]
97 : bates 435 }
98 : bates 452 fixed.form <- nobars(formula)
99 :     if (!inherits(fixed.form, "formula")) fixed.form <- ~ 1 # default formula
100 : bates 571 Xmat <- model.matrix(fixed.form, frm)
101 : bates 435 mmats <- c(lapply(random, "[[", 1),
102 : bates 571 .fixed = list(cbind(Xmat, .response = model.response(frm))))
103 : bates 689 obj <- .Call("lmer_create", lapply(random, "[[", 2),
104 :     mmats, PACKAGE = "Matrix")
105 : bates 691 slot(obj, "frame") <- frm
106 : bates 689 slot(obj, "terms") <- attr(model.frame(fixed.form, data), "terms")
107 :     slot(obj, "assign") <- attr(Xmat, "assign")
108 :     slot(obj, "call") <- match.call()
109 :     slot(obj, "REML") <- REML
110 : bates 571 rm(Xmat)
111 : bates 435 .Call("lmer_initial", obj, PACKAGE="Matrix")
112 :     .Call("lmer_ECMEsteps", obj,
113 :     controlvals$niterEM,
114 :     controlvals$REML,
115 :     controlvals$EMverbose,
116 :     PACKAGE = "Matrix")
117 :     LMEoptimize(obj) <- controlvals
118 : bates 689 slot(obj, "residuals") <-
119 :     unname(model.response(frm) -
120 :     (slot(obj, "fitted") <-
121 :     .Call("lmer_fitted", obj, mmats, TRUE, PACKAGE = "Matrix")))
122 : bates 435 obj
123 :     })
124 :    
125 : bates 413 setReplaceMethod("LMEoptimize", signature(x="lmer", value="list"),
126 : bates 316 function(x, value)
127 :     {
128 :     if (value$msMaxIter < 1) return(x)
129 :     nc <- x@nc
130 :     nc <- nc[1:(length(nc) - 2)]
131 :     constr <- unlist(lapply(nc, function(k) 1:((k*(k+1))/2) <= k))
132 : bates 752 fn <- function(pars)
133 :     deviance(.Call("lmer_coefGets", x, pars,
134 :     2, PACKAGE = "Matrix"),
135 :     REML = value$REML)
136 : bates 380 gr <- if (value$analyticGradient)
137 :     function(pars) {
138 : bates 752 if (!isTRUE(all.equal(pars,
139 :     .Call("lmer_coef", x, 2))))
140 :     .Call("lmer_coefGets", x, pars, 2)
141 :     .Call("lmer_gradient", x, value$REML, 2)
142 : bates 380 } else NULL
143 : bates 752 RV <- lapply(R.Version()[c("major", "minor")], as.numeric)
144 :     if ((RV$major > 1 && RV$minor >= 2.0) ||
145 :     require("port", quietly = TRUE)) {
146 :     optimRes <- nlminb(.Call("lmer_coef", x, 2),
147 :     fn, gr,
148 :     lower = ifelse(constr, 1e-10, -Inf),
149 :     control = list(iter.max = value$msMaxIter,
150 :     trace = as.integer(value$msVerbose)))
151 : bates 751 } else {
152 : bates 752 optimRes <- optim(.Call("lmer_coef", x, 2), fn, gr,
153 : bates 751 method = "L-BFGS-B",
154 :     lower = ifelse(constr, 1e-10, -Inf),
155 :     control = list(maxit = value$msMaxIter,
156 :     trace = as.integer(value$msVerbose)))
157 :     }
158 : bates 752 .Call("lmer_coefGets", x, optimRes$par, 2)
159 : bates 316 if (optimRes$convergence != 0) {
160 :     warning(paste("optim returned message",optimRes$message,"\n"))
161 :     }
162 :     return(x)
163 :     })
164 :    
165 : bates 413 setMethod("ranef", signature(object = "lmer"),
166 : bates 689 function(object, accumulate = FALSE, ...) {
167 :     val <- new("lmer.ranef",
168 :     lapply(.Call("lmer_ranef", object, PACKAGE = "Matrix"),
169 :     data.frame, check.names = FALSE),
170 :     varFac = object@bVar,
171 :     stdErr = .Call("lmer_sigma", object,
172 :     object@REML, PACKAGE = "Matrix"))
173 :     if (!accumulate || length(val@varFac) == 1) return(val)
174 :     ## check for nested factors
175 :     L <- object@L
176 :     if (any(sapply(seq(a = val), function(i) length(L[[Lind(i,i)]]@i))))
177 :     error("Require nested grouping factors to accumulate random effects")
178 :     val
179 : bates 316 })
180 :    
181 : bates 413 setMethod("fixef", signature(object = "lmer"),
182 : bates 316 function(object, ...) {
183 : bates 550 val <- .Call("lmer_fixef", object, PACKAGE = "Matrix")
184 : bates 316 val[-length(val)]
185 :     })
186 :    
187 : deepayan 721 setMethod("fixef", signature(object = "glmer"),
188 :     function(object, ...) {
189 :     object@fixed
190 :     })
191 :    
192 : bates 413 setMethod("VarCorr", signature(x = "lmer"),
193 : bates 316 function(x, REML = TRUE, useScale = TRUE, ...) {
194 : bates 550 val <- .Call("lmer_variances", x, PACKAGE = "Matrix")
195 : bates 316 for (i in seq(along = val)) {
196 :     dimnames(val[[i]]) = list(x@cnames[[i]], x@cnames[[i]])
197 :     val[[i]] = as(as(val[[i]], "pdmatrix"), "corrmatrix")
198 :     }
199 :     new("VarCorr",
200 : bates 449 scale = .Call("lmer_sigma", x, REML, PACKAGE = "Matrix"),
201 : bates 316 reSumry = val,
202 :     useScale = useScale)
203 :     })
204 :    
205 : bates 413 setMethod("gradient", signature(x = "lmer"),
206 : bates 316 function(x, REML, unconst, ...)
207 : bates 449 .Call("lmer_gradient", x, REML, unconst, PACKAGE = "Matrix"))
208 : bates 316
209 : bates 449 setMethod("summary", signature(object = "lmer"),
210 :     function(object, ...)
211 : bates 727 new("summary.lmer", object, useScale = TRUE,
212 :     showCorrelation = TRUE,
213 :     method = if (object@REML) "REML" else "ML",
214 :     family = gaussian(),
215 :     logLik = logLik(object),
216 :     fixed = fixef(object)))
217 : bates 316
218 : deepayan 721 ## FIXME: glmm-s with scale not handled
219 :     setMethod("summary", signature(object = "glmer"),
220 :     function(object, ...)
221 : bates 727 new("summary.lmer", object, useScale = FALSE,
222 :     showCorrelation = TRUE,
223 :     method = object@method,
224 :     family = object@family,
225 :     logLik = logLik(object),
226 :     fixed = fixef(object)))
227 : deepayan 721
228 : bates 449 setMethod("show", signature(object = "lmer"),
229 :     function(object)
230 : bates 550 show(new("summary.lmer", object, useScale = TRUE,
231 : bates 727 showCorrelation = FALSE,
232 :     method = if (object@REML) "REML" else "ML",
233 :     family = gaussian(),
234 :     logLik = logLik(object),
235 :     fixed = fixef(object)))
236 : bates 449 )
237 : bates 727
238 : deepayan 721 setMethod("show", signature(object = "glmer"),
239 :     function(object)
240 :     show(new("summary.lmer", object, useScale = FALSE,
241 : bates 727 showCorrelation = FALSE,
242 :     method = object@method,
243 :     family = object@family,
244 :     logLik = logLik(object),
245 :     fixed = fixef(object)))
246 : deepayan 721 )
247 : bates 449
248 :     setMethod("show", "summary.lmer",
249 : bates 316 function(object) {
250 : bates 727 fcoef <- object@fixed
251 : bates 449 useScale <- object@useScale
252 :     corF <- as(as(vcov(object, useScale = useScale), "pdmatrix"),
253 : bates 316 "corrmatrix")
254 :     DF <- getFixDF(object)
255 :     coefs <- cbind(fcoef, corF@stdDev, DF)
256 :     nc <- object@nc
257 :     dimnames(coefs) <-
258 :     list(names(fcoef), c("Estimate", "Std. Error", "DF"))
259 : bates 449 digits <- max(3, getOption("digits") - 2)
260 :     REML <- length(object@REML) > 0 && object@REML[1]
261 : bates 727 llik <- object@logLik
262 : bates 449 dev <- object@deviance
263 :    
264 :     rdig <- 5
265 : bates 727 if (glz <- !(object@method %in% c("REML", "ML"))) {
266 :     cat(paste("Generalized linear mixed model fit using",
267 :     object@method, "\n"))
268 :     } else {
269 :     cat("Linear mixed-effects model fit by ")
270 :     cat(if(object@REML) "REML\n" else "maximum likelihood\n")
271 :     }
272 : bates 449 if (!is.null(object@call$formula)) {
273 :     cat("Formula:", deparse(object@call$formula),"\n")
274 :     }
275 :     if (!is.null(object@call$data)) {
276 :     cat(" Data:", deparse(object@call$data), "\n")
277 :     }
278 :     if (!is.null(object@call$subset)) {
279 :     cat(" Subset:",
280 :     deparse(asOneSidedFormula(object@call$subset)[[2]]),"\n")
281 :     }
282 : bates 727 if (glz) {
283 : bates 750 cat(" Family: ", object@family$family, "(",
284 :     object@family$link, " link)\n", sep = "")
285 : bates 727 print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
286 : bates 449 logLik = c(llik),
287 : bates 727 deviance = -2*llik,
288 :     row.names = ""))
289 :     } else {
290 :     print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
291 :     logLik = c(llik),
292 : bates 750 MLdeviance = dev["ML"],
293 : bates 449 REMLdeviance = dev["REML"],
294 :     row.names = ""))
295 : bates 727 }
296 : bates 449 cat("Random effects:\n")
297 :     show(VarCorr(object))
298 :     ngrps <- lapply(object@flist, function(x) length(levels(x)))
299 :     cat(sprintf("# of obs: %d, groups: ", object@nc[length(object@nc)]))
300 :     cat(paste(paste(names(ngrps), ngrps, sep = ", "), collapse = "; "))
301 :     cat("\n")
302 :     if (!useScale)
303 :     cat("\nEstimated scale (compare to 1) ",
304 :     .Call("lmer_sigma", object, object@REML, PACKAGE = "Matrix"),
305 :     "\n")
306 :     if (nrow(coefs) > 0) {
307 :     if (useScale) {
308 :     stat <- coefs[,1]/coefs[,2]
309 :     pval <- 2*pt(abs(stat), coefs[,3], lower = FALSE)
310 :     nms <- colnames(coefs)
311 :     coefs <- cbind(coefs, stat, pval)
312 :     colnames(coefs) <- c(nms, "t value", "Pr(>|t|)")
313 :     } else {
314 :     coefs <- coefs[, 1:2, drop = FALSE]
315 :     stat <- coefs[,1]/coefs[,2]
316 :     pval <- 2*pnorm(abs(stat), lower = FALSE)
317 :     nms <- colnames(coefs)
318 :     coefs <- cbind(coefs, stat, pval)
319 :     colnames(coefs) <- c(nms, "z value", "Pr(>|z|)")
320 :     }
321 :     cat("\nFixed effects:\n")
322 :     printCoefmat(coefs, tst.ind = 4, zap.ind = 3)
323 :     if (length(object@showCorrelation) > 0 && object@showCorrelation[1]) {
324 :     rn <- rownames(coefs)
325 :     dimnames(corF) <- list(
326 :     abbreviate(rn, minlen=11),
327 :     abbreviate(rn, minlen=6))
328 :     if (!is.null(corF)) {
329 :     p <- NCOL(corF)
330 :     if (p > 1) {
331 :     cat("\nCorrelation of Fixed Effects:\n")
332 :     corF <- format(round(corF, 3), nsmall = 3)
333 :     corF[!lower.tri(corF)] <- ""
334 :     print(corF[-1, -p, drop=FALSE], quote = FALSE)
335 :     }
336 :     }
337 :     }
338 :     }
339 :     invisible(object)
340 : bates 316 })
341 :    
342 : deepayan 707
343 : bates 689 setMethod("lmer", signature(formula = "formula"),
344 :     function(formula, family, data,
345 :     method = c("REML", "ML", "PQL", "Laplace", "AGQ"),
346 :     control = list(),
347 :     subset, weights, na.action, offset,
348 :     model = TRUE, x = FALSE, y = FALSE, ...)
349 :     {
350 : bates 704 if (missing(method)) {
351 :     method <- "PQL"
352 :     } else {
353 :     method <- match.arg(method)
354 :     if (method == "ML") method <- "PQL"
355 :     if (method == "REML")
356 :     warning(paste('Argument method = "REML" is not meaningful',
357 :     'for a generalized linear mixed model.',
358 :     '\nUsing method = "PQL".\n'))
359 :     }
360 : deepayan 707 ## if (method %in% c("Laplace", "AGQ"))
361 :     ## stop("Laplace and AGQ methods not yet implemented")
362 :     if (method %in% c("AGQ"))
363 :     stop("AGQ method not yet implemented")
364 : bates 689 gVerb <- getOption("verbose")
365 :     # match and check parameters
366 :     controlvals <- do.call("lmerControl", control)
367 :     controlvals$REML <- FALSE
368 :     if (length(formula) < 3) stop("formula must be a two-sided formula")
369 :     ## initial glm fit
370 :     mf <- match.call()
371 :     m <- match(c("family", "data", "subset", "weights",
372 :     "na.action", "offset"),
373 :     names(mf), 0)
374 :     mf <- mf[c(1, m)]
375 :     mf[[1]] <- as.name("glm")
376 :     fixed.form <- nobars(formula)
377 :     if (!inherits(fixed.form, "formula")) fixed.form <- ~ 1 # default formula
378 :     environment(fixed.form) <- environment(formula)
379 :     mf$formula <- fixed.form
380 :     mf$x <- mf$model <- mf$y <- TRUE
381 :     glm.fit <- eval(mf, parent.frame())
382 :     family <- glm.fit$family
383 :     ## Note: offset is on the linear scale
384 :     offset <- glm.fit$offset
385 :     if (is.null(offset)) offset <- 0
386 :     weights <- sqrt(abs(glm.fit$prior.weights))
387 :     ## initial 'fitted' values on linear scale
388 :     etaold <- eta <- glm.fit$linear.predictors
389 :    
390 :     ## evaluation of model frame
391 :     mf$x <- mf$model <- mf$y <- mf$family <- NULL
392 :     mf$drop.unused.levels <- TRUE
393 :     this.form <- subbars(formula)
394 :     environment(this.form) <- environment(formula)
395 :     mf$formula <- this.form
396 :     mf[[1]] <- as.name("model.frame")
397 :     frm <- eval(mf, parent.frame())
398 :    
399 :     ## grouping factors and model matrices for random effects
400 :     bars <- findbars(formula[[3]])
401 :     random <-
402 :     lapply(bars,
403 :     function(x) list(model.matrix(eval(substitute(~term,
404 :     list(term=x[[2]]))),
405 :     frm),
406 :     eval(substitute(as.factor(fac)[,drop = TRUE],
407 :     list(fac = x[[3]])), frm)))
408 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
409 :    
410 :     ## order factor list by decreasing number of levels
411 :     nlev <- sapply(random, function(x) length(levels(x[[2]])))
412 :     if (any(diff(nlev) > 0)) {
413 :     random <- random[rev(order(nlev))]
414 :     }
415 :     mmats <- c(lapply(random, "[[", 1),
416 :     .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
417 :     ## FIXME: Use Xfrm and Xmat to get the terms and assign
418 :     ## slots, pass these to lmer_create, then destroy Xfrm, Xmat, etc.
419 : bates 691 obj <- .Call("lmer_create", lapply(random, "[[", 2),
420 :     mmats, PACKAGE = "Matrix")
421 :     slot(obj, "frame") <- frm
422 :     slot(obj, "terms") <- attr(glm.fit$model, "terms")
423 :     slot(obj, "assign") <- attr(glm.fit$x, "assign")
424 :     slot(obj, "call") <- match.call()
425 :     slot(obj, "REML") <- FALSE
426 : bates 689 rm(glm.fit)
427 :     .Call("lmer_initial", obj, PACKAGE="Matrix")
428 :     mmats.unadjusted <- mmats
429 :     mmats[[1]][1,1] <- mmats[[1]][1,1]
430 :     conv <- FALSE
431 :     firstIter <- TRUE
432 :     msMaxIter.orig <- controlvals$msMaxIter
433 :     responseIndex <- ncol(mmats$.fixed)
434 :    
435 :     for (iter in seq(length = controlvals$PQLmaxIt))
436 :     {
437 :     mu <- family$linkinv(eta)
438 :     dmu.deta <- family$mu.eta(eta)
439 :     ## weights (note: weights is already square-rooted)
440 :     w <- weights * dmu.deta / sqrt(family$variance(mu))
441 :     ## adjusted response (should be comparable to X \beta, not including offset
442 :     z <- eta - offset + (mmats.unadjusted$.fixed[, responseIndex] - mu) / dmu.deta
443 :     .Call("nlme_weight_matrix_list",
444 :     mmats.unadjusted, w, z, mmats, PACKAGE="Matrix")
445 :     .Call("lmer_update_mm", obj, mmats, PACKAGE="Matrix")
446 :     if (firstIter) {
447 :     .Call("lmer_initial", obj, PACKAGE="Matrix")
448 :     if (gVerb) cat(" PQL iterations convergence criterion\n")
449 :     }
450 :     .Call("lmer_ECMEsteps", obj,
451 :     controlvals$niterEM,
452 :     FALSE,
453 :     controlvals$EMverbose,
454 :     PACKAGE = "Matrix")
455 :     LMEoptimize(obj) <- controlvals
456 :     eta[] <- offset + ## FIXME: should the offset be here ?
457 :     .Call("lmer_fitted", obj,
458 :     mmats.unadjusted, TRUE, PACKAGE = "Matrix")
459 :     crit <- max(abs(eta - etaold)) / (0.1 + max(abs(eta)))
460 :     if (gVerb) cat(sprintf("%03d: %#11g\n", as.integer(iter), crit))
461 :     ## use this to determine convergence
462 :     if (crit < controlvals$tolerance) {
463 :     conv <- TRUE
464 :     break
465 :     }
466 :     etaold[] <- eta
467 :    
468 :     ## Changing number of iterations on second and
469 :     ## subsequent iterations.
470 :     if (firstIter)
471 :     {
472 :     controlvals$niterEM <- 2
473 :     controlvals$msMaxIter <- 10
474 :     firstIter <- FALSE
475 :     }
476 :     }
477 :     if (!conv) warning("IRLS iterations for glmm did not converge")
478 : deepayan 706 controlvals$msMaxIter <- msMaxIter.orig
479 :    
480 :    
481 : deepayan 707 ### if (TRUE) ## Laplace
482 :     ### {
483 :     ## Need to optimize L(theta, beta) using Laplace approximation
484 : deepayan 706
485 : deepayan 707 ## Things needed for that:
486 :     ##
487 :     ## 1. reduced ssclme object, offset, weighted model matrices
488 :     ## 2. facs, reduced model matrices
489 : deepayan 706
490 : deepayan 707 ## Of these, those in 2 will be fixed given theta and beta,
491 :     ## and can be thought of arguments to the L(theta, beta)
492 :     ## function. However, the ones in 1 will have the same
493 :     ## structure. So the plan is to pre-allocate them and pass
494 :     ## them in too so they can be used without creating/copying
495 :     ## them more than once
496 : deepayan 706
497 :    
498 : deepayan 707 ## reduced ssclme
499 : deepayan 706
500 : deepayan 707 reducedObj <- .Call("lmer_collapse", obj, PACKAGE = "Matrix")
501 :     reducedMmats.unadjusted <- mmats.unadjusted
502 :     reducedMmats.unadjusted$.fixed <-
503 :     reducedMmats.unadjusted$.fixed[, responseIndex, drop = FALSE]
504 :     reducedMmats <- mmats
505 :     reducedMmats$.fixed <-
506 :     reducedMmats$.fixed[, responseIndex, drop = FALSE]
507 : deepayan 706
508 : deepayan 707 ## define function that calculates bhats given theta and beta
509 : deepayan 706
510 : deepayan 707 bhat <-
511 :     function(pars = NULL) # 1:(responseIndex-1) - beta, rest - theta
512 :     {
513 :     if (is.null(pars))
514 : deepayan 706 {
515 : deepayan 707 off <- drop(mmats.unadjusted$.fixed %*%
516 :     c(fixef(obj), 0)) + offset
517 :     }
518 :     else
519 :     {
520 :     .Call("lmer_coefGets",
521 :     reducedObj,
522 :     as.double(pars[responseIndex:length(pars)]),
523 :     TRUE,
524 :     PACKAGE = "Matrix")
525 :     off <- drop(mmats.unadjusted$.fixed %*%
526 :     c(pars[1:(responseIndex-1)], 0)) + offset
527 :     }
528 :     niter <- 20
529 :     conv <- FALSE
530 : deepayan 706
531 : deepayan 707 eta <- offset +
532 :     .Call("lmer_fitted",
533 :     obj, mmats.unadjusted, TRUE,
534 :     PACKAGE = "Matrix")
535 :     etaold <- eta
536 :    
537 :     for (iter in seq(length = niter))
538 :     {
539 :     mu <- family$linkinv(eta)
540 :     dmu.deta <- family$mu.eta(eta)
541 :     w <- weights * dmu.deta / sqrt(family$variance(mu))
542 :     z <- eta - off + (reducedMmats.unadjusted$.fixed[, 1]
543 :     - mu) / dmu.deta
544 :     .Call("nlme_weight_matrix_list",
545 :     reducedMmats.unadjusted, w, z, reducedMmats,
546 :     PACKAGE="Matrix")
547 :     .Call("lmer_update_mm",
548 :     reducedObj, reducedMmats,
549 :     PACKAGE="Matrix")
550 :     eta[] <- off +
551 :     .Call("lmer_fitted", reducedObj,
552 :     reducedMmats.unadjusted, TRUE,
553 : deepayan 706 PACKAGE = "Matrix")
554 : deepayan 707 ##cat(paste("bhat Criterion:", max(abs(eta - etaold)) /
555 :     ## (0.1 + max(abs(eta))), "\n"))
556 :     ## use this to determine convergence
557 :     if (max(abs(eta - etaold)) <
558 :     (0.1 + max(abs(eta))) * controlvals$tolerance)
559 : deepayan 706 {
560 : deepayan 707 conv <- TRUE
561 :     break
562 : deepayan 706 }
563 : deepayan 707 etaold[] <- eta
564 :    
565 :     }
566 :     if (!conv) warning("iterations for bhat did not converge")
567 : deepayan 706
568 : deepayan 707 ## bhat doesn't really need to return anything, we
569 :     ## just want the side-effect of modifying reducedObj
570 :     ## In particular, we are interested in
571 :     ## ranef(reducedObj) and reducedObj@bVar (?). But
572 :     ## the mu-scale response will be useful for log-lik
573 :     ## calculations later, so return them anyway
574 : deepayan 706
575 : deepayan 707 invisible(family$linkinv(eta))
576 :     }
577 : deepayan 706
578 : deepayan 707 ## function that calculates log likelihood (the thing that
579 :     ## needs to get evaluated at each Gauss-Hermite location)
580 :    
581 :     ## log scale ? worry about details later, get the pieces in place
582 :    
583 :     ## this is for the Laplace approximation only. GH is more
584 :     ## complicated
585 :    
586 :     devLaplace <- function(pars = NULL)
587 :     {
588 :     ## FIXME: This actually returns half the deviance.
589 : deepayan 706
590 : deepayan 707 ## gets correct values of bhat and bvars. As a side
591 :     ## effect, mu now has fitted values
592 :     mu <- bhat(pars = pars)
593 :    
594 :     ## GLM family log likelihood (upto constant ?)(log scale)
595 :     ## FIXME: need to adjust for sigma^2 for appropriate models (not trivial!)
596 :    
597 :     ## Keep everything on (log) likelihood scale
598 : deepayan 706
599 : deepayan 707 ## log lik from observations given fixed and random effects
600 :     ## get deviance, then multiply by -1/2 (since deviance = -2 log lik)
601 :     ans <- -sum(family$dev.resids(y = mmats.unadjusted$.fixed[, responseIndex],
602 :     mu = mu,
603 :     wt = weights^2))/2
604 :    
605 : deepayan 717 ## if (is.null(getOption("laplaceinR")))
606 :     ## {
607 :     ans <- ans +
608 :     .Call("lmer_laplace_devComp", reducedObj,
609 :     PACKAGE = "Matrix")
610 :     ## }
611 :     ## else
612 :     ## {
613 :     ## ranefs <- .Call("lmer_ranef", reducedObj, PACKAGE = "Matrix")
614 :     ## ## ans <- ans + reducedObj@devComp[2]/2 # log-determinant of Omega
615 : deepayan 706
616 : deepayan 717 ## Omega <- reducedObj@Omega
617 :     ## for (i in seq(along = ranefs))
618 :     ## {
619 :     ## ## contribution for random effects (get it working,
620 :     ## ## optimize later)
621 :     ## ## symmetrize RE variance
622 :     ## Omega[[i]] <- Omega[[i]] + t(Omega[[i]])
623 :     ## diag(Omega[[i]]) <- diag(Omega[[i]]) / 2
624 : deepayan 706
625 : deepayan 717 ## ## want log of `const det(Omega) exp(-1/2 b'
626 :     ## ## Omega b )` i.e., const + log det(Omega) - .5
627 :     ## ## * (b' Omega b)
628 : deepayan 706
629 : deepayan 717 ## ## FIXME: need to adjust for sigma^2 for appropriate
630 :     ## ## models (easy). These are all the b'Omega b,
631 :     ## ## summed as they eventually need to be. Think of
632 :     ## ## this as sum(rowSums((ranefs[[i]] %*% Omega[[i]])
633 :     ## ## * ranefs[[i]]))
634 : deepayan 706
635 : deepayan 717 ## ranef.loglik.det <- nrow(ranefs[[i]]) *
636 :     ## determinant(Omega[[i]], logarithm = TRUE)$modulus/2
637 : deepayan 711
638 : deepayan 717 ## # print(ranef.loglik.det)
639 : deepayan 711
640 : deepayan 717 ## ranef.loglik.re <-
641 :     ## -sum((ranefs[[i]] %*% Omega[[i]]) * ranefs[[i]])/2
642 : deepayan 711
643 : deepayan 717 ## # print(ranef.loglik.re)
644 : deepayan 711
645 : deepayan 717 ## ranef.loglik <- ranef.loglik.det + ranef.loglik.re
646 : deepayan 706
647 : deepayan 717 ## ## Jacobian adjustment
648 :     ## log.jacobian <-
649 :     ## sum(log(abs(apply(reducedObj@bVar[[i]],
650 :     ## 3,
651 : deepayan 706
652 : deepayan 717 ## ## next line depends on
653 :     ## ## whether bVars are variances
654 :     ## ## or Cholesly factors
655 : deepayan 706
656 : deepayan 717 ## ## function(x) sum(diag(x)))
657 :     ## ## Was this a bug? function(x) sum(diag( La.chol( x ) )))
658 :     ## function(x) prod(diag( La.chol( x ) )))
659 :     ## )))
660 : deepayan 706
661 : deepayan 717 ## # print(log.jacobian)
662 : deepayan 711
663 :    
664 : deepayan 717 ## ## the constant terms from the r.e. and the final
665 :     ## ## Laplacian integral cancel out both being:
666 :     ## ## ranef.loglik.constant <- 0.5 * length(ranefs[[i]]) * log(2 * base::pi)
667 : deepayan 710
668 : deepayan 717 ## ans <- ans + ranef.loglik + log.jacobian
669 :     ## }
670 :     ## }
671 : deepayan 707 ## ans is (up to some constant) log of the Laplacian
672 :     ## approximation of the likelihood. Return it's negative
673 :     ## to be minimized
674 : deepayan 706
675 : deepayan 707 ## cat("Parameters: ")
676 :     ## print(pars)
677 :    
678 :     ## cat("Value: ")
679 :     ## print(as.double(-ans))
680 :    
681 :     -ans
682 :     }
683 :    
684 :     if (method == "Laplace")
685 :     {
686 : bates 752 RV <- lapply(R.Version()[c("major", "minor")], as.numeric)
687 :     if ((RV$major > 1 && RV$minor >= 2.0) ||
688 :     require("port", quietly = TRUE)) {
689 : bates 751 optimRes <-
690 : bates 752 nlminb(c(fixef(obj),
691 :     .Call("lmer_coef", obj, TRUE, PACKAGE = "Matrix")),
692 :     devLaplace,
693 :     control = list(trace = getOption("verbose"),
694 :     iter.max = controlvals$msMaxIter))
695 : bates 751 optpars <- optimRes$par
696 :     } else {
697 :     optimRes <-
698 :     optim(fn =
699 :     c(fixef(obj), .Call("lmer_coef", obj, TRUE,
700 :     PACKAGE = "Matrix")),
701 :     devLaplace,
702 :     method = "BFGS", hessian = TRUE,
703 :     control = list(trace = getOption("verbose"),
704 :     reltol = controlvals$msTol,
705 :     maxit = controlvals$msMaxIter))
706 :     optpars <- optimRes$par
707 :     Hessian <- optimRes$hessian
708 :     }
709 : deepayan 707 if (optimRes$convergence != 0)
710 :     warning("optim failed to converge")
711 : bates 751
712 : deepayan 707 ##fixef(obj) <- optimRes$par[seq(length = responseIndex - 1)]
713 :     if (getOption("verbose")) {
714 :     cat(paste("optim convergence code",
715 :     optimRes$convergence, "\n"))
716 :     cat("Fixed effects:\n")
717 :     print(fixef(obj))
718 :     print(optimRes$par[seq(length = responseIndex - 1)])
719 :     cat("(Unconstrained) variance coefficients:\n")
720 : deepayan 706
721 : deepayan 707 print(
722 : deepayan 706 .Call("lmer_coef",
723 :     obj,
724 :     TRUE,
725 :     PACKAGE = "Matrix"))
726 : deepayan 707
727 :     ##coef(obj, unconst = TRUE) <-
728 :     ## optimRes$par[responseIndex:length(optimRes$par)]
729 :     ##print(coef(obj, unconst = TRUE))
730 :     print( optimRes$par[responseIndex:length(optimRes$par)] )
731 : deepayan 706 }
732 : deepayan 707
733 :     ## need to calculate likelihood. also need to store
734 :     ## new estimates of fixed effects somewhere
735 :     ## (probably cannot update standard errors)
736 : deepayan 717 ###Rprof(NULL)
737 : deepayan 707 }
738 :     else
739 :     {
740 :     optpars <-
741 :     c(fixef(obj),
742 :     .Call("lmer_coef",
743 :     obj,
744 :     TRUE,
745 :     PACKAGE = "Matrix"))
746 :     Hessian <- new("matrix")
747 :     }
748 : deepayan 706
749 :    
750 : deepayan 707 ## Before finishing, we need to call devLaplace with the
751 :     ## optimum pars to get the final log likelihood (still need
752 :     ## to make sure it's the actual likelihood and not a
753 :     ## multiple). This would automatically call bhat() and hence
754 :     ## have the 'correct' random effects in reducedObj.
755 : deepayan 706
756 : deepayan 721 loglik <- -devLaplace(optpars)
757 : deepayan 717 ##print(loglik)
758 : deepayan 707 ff <- optpars[1:(responseIndex-1)]
759 :     names(ff) <- names(fixef(obj))
760 : deepayan 706
761 : deepayan 707 if (!x) mmats <- list()
762 : deepayan 706
763 : deepayan 707 ### }
764 : deepayan 706
765 : deepayan 721 ##obj
766 :    
767 :     new("glmer", obj,
768 :     family = family,
769 :     glmmll = loglik,
770 :     method = method,
771 :     fixed = ff)
772 : bates 689 })
773 :    
774 : deepayan 707
775 : bates 316 ## calculates degrees of freedom for fixed effects Wald tests
776 :     ## This is a placeholder. The answers are generally wrong. It will
777 :     ## be very tricky to decide what a 'right' answer should be with
778 :     ## crossed random effects.
779 :    
780 : bates 413 setMethod("getFixDF", signature(object="lmer"),
781 : bates 316 function(object, ...)
782 :     {
783 :     nc <- object@nc[-seq(along = object@Omega)]
784 :     p <- nc[1] - 1
785 :     n <- nc[2]
786 :     rep(n-p, p)
787 :     })
788 :    
789 : bates 446 setMethod("logLik", signature(object="lmer"),
790 :     function(object, REML = object@REML, ...) {
791 :     val <- -deviance(object, REML = REML)/2
792 :     nc <- object@nc[-seq(a = object@Omega)]
793 :     attr(val, "nall") <- attr(val, "nobs") <- nc[2]
794 : bates 752 attr(val, "df") <-
795 :     nc[1] + length(.Call("lmer_coef", object, 2))
796 : bates 446 attr(val, "REML") <- REML
797 :     class(val) <- "logLik"
798 :     val
799 :     })
800 :    
801 : deepayan 721 setMethod("logLik", signature(object="glmer"),
802 :     function(object, ...) {
803 :     val <- object@glmmll
804 :     nc <- object@nc[-seq(a = object@Omega)]
805 :     attr(val, "nall") <- attr(val, "nobs") <- nc[2]
806 : bates 752 attr(val, "df") <-
807 :     nc[1] + length(.Call("lmer_coef", object, 2))
808 : deepayan 721 class(val) <- "logLik"
809 :     val
810 :     })
811 :    
812 : bates 446 setMethod("anova", signature(object = "lmer"),
813 :     function(object, ...)
814 :     {
815 :     mCall <- match.call(expand.dots = TRUE)
816 :     dots <- list(...)
817 :     modp <- logical(0)
818 :     if (length(dots))
819 :     modp <- sapply(dots, inherits, "lmer") | sapply(dots, inherits, "lm")
820 :     if (any(modp)) { # multiple models - form table
821 :     opts <- dots[!modp]
822 :     mods <- c(list(object), dots[modp])
823 :     names(mods) <- sapply(as.list(mCall)[c(FALSE, TRUE, modp)], as.character)
824 :     mods <- mods[order(sapply(lapply(mods, logLik, REML = FALSE), attr, "df"))]
825 :     calls <- lapply(mods, slot, "call")
826 :     data <- lapply(calls, "[[", "data")
827 :     if (any(data != data[[1]])) stop("all models must be fit to the same data object")
828 :     header <- paste("Data:", data[[1]])
829 :     subset <- lapply(calls, "[[", "subset")
830 :     if (any(subset != subset[[1]])) stop("all models must use the same subset")
831 :     if (!is.null(subset[[1]]))
832 :     header <-
833 :     c(header, paste("Subset", deparse(subset[[1]]), sep = ": "))
834 :     llks <- lapply(mods, logLik, REML = FALSE)
835 :     Df <- sapply(llks, attr, "df")
836 :     llk <- unlist(llks)
837 :     chisq <- 2 * pmax(0, c(NA, diff(llk)))
838 :     dfChisq <- c(NA, diff(Df))
839 :     val <- data.frame(Df = Df,
840 :     AIC = sapply(llks, AIC),
841 :     BIC = sapply(llks, BIC),
842 :     logLik = llk,
843 :     "Chisq" = chisq,
844 :     "Chi Df" = dfChisq,
845 :     "Pr(>Chisq)" = pchisq(chisq, dfChisq, lower = FALSE),
846 :     check.names = FALSE)
847 :     class(val) <- c("anova", class(val))
848 :     attr(val, "heading") <-
849 : bates 690 c(header, "Models:",
850 : bates 446 paste(names(mods),
851 :     unlist(lapply(lapply(calls, "[[", "formula"), deparse)),
852 : bates 690 sep = ": "))
853 : bates 446 return(val)
854 :     } else {
855 : bates 571 foo <- object
856 :     foo@status["factored"] <- FALSE
857 :     .Call("lmer_factor", foo, PACKAGE="Matrix")
858 :     dfr <- getFixDF(foo)
859 :     rcol <- ncol(foo@RXX)
860 :     ss <- foo@RXX[ , rcol]^2
861 :     ssr <- ss[[rcol]]
862 :     ss <- ss[seq(along = dfr)]
863 :     names(ss) <- object@cnames[[".fixed"]][seq(along = dfr)]
864 :     asgn <- foo@assign
865 :     terms <- foo@terms
866 :     nmeffects <- attr(terms, "term.labels")
867 :     if ("(Intercept)" %in% names(ss))
868 :     nmeffects <- c("(Intercept)", nmeffects)
869 :     ss <- unlist(lapply(split(ss, asgn), sum))
870 :     df <- unlist(lapply(split(asgn, asgn), length))
871 :     dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
872 :     ms <- ss/df
873 :     f <- ms/(ssr/dfr)
874 :     P <- pf(f, df, dfr, lower.tail = FALSE)
875 :     table <- data.frame(df, ss, ms, dfr, f, P)
876 :     dimnames(table) <-
877 :     list(nmeffects,
878 :     c("Df", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
879 :     if ("(Intercept)" %in% nmeffects) table <- table[-1,]
880 :     attr(table, "heading") <- "Analysis of Variance Table"
881 :     class(table) <- c("anova", "data.frame")
882 :     table
883 : bates 446 }
884 : bates 316 })
885 : bates 446
886 :     setMethod("update", signature(object = "lmer"),
887 :     function(object, formula., ..., evaluate = TRUE)
888 :     {
889 :     call <- object@call
890 :     if (is.null(call))
891 :     stop("need an object with call component")
892 :     extras <- match.call(expand.dots = FALSE)$...
893 :     if (!missing(formula.))
894 :     call$formula <- update.formula(formula(object), formula.)
895 :     if (length(extras) > 0) {
896 :     existing <- !is.na(match(names(extras), names(call)))
897 :     for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
898 :     if (any(!existing)) {
899 :     call <- c(as.list(call), extras[!existing])
900 :     call <- as.call(call)
901 :     }
902 :     }
903 :     if (evaluate)
904 :     eval(call, parent.frame())
905 :     else call
906 :     })
907 :    
908 :    
909 :     setMethod("confint", signature(object = "lmer"),
910 :     function (object, parm, level = 0.95, ...)
911 :     {
912 :     cf <- fixef(object)
913 :     pnames <- names(cf)
914 :     if (missing(parm))
915 :     parm <- seq(along = pnames)
916 :     else if (is.character(parm))
917 :     parm <- match(parm, pnames, nomatch = 0)
918 :     a <- (1 - level)/2
919 :     a <- c(a, 1 - a)
920 :     pct <- paste(round(100 * a, 1), "%")
921 :     ci <- array(NA, dim = c(length(parm), 2),
922 :     dimnames = list(pnames[parm], pct))
923 :     ses <- sqrt(diag(vcov(object)))[parm]
924 : bates 449 ci[] <- cf[parm] + ses * t(outer(a, getFixDF(object)[parm], qt))
925 : bates 446 ci
926 :     })
927 :    
928 : bates 689 setMethod("param", signature(object = "lmer"),
929 : bates 449 function(object, unconst = FALSE, ...) {
930 :     .Call("lmer_coef", object, unconst, PACKAGE = "Matrix")
931 :     })
932 : bates 446
933 : bates 449 setMethod("deviance", "lmer",
934 :     function(object, REML = NULL, ...) {
935 :     .Call("lmer_factor", object, PACKAGE = "Matrix")
936 :     if (is.null(REML))
937 :     REML <- if (length(oR <- object@REML)) oR else FALSE
938 :     object@deviance[[ifelse(REML, "REML", "ML")]]
939 :     })
940 : bates 446
941 : deepayan 721
942 :     setMethod("deviance", "glmer",
943 :     function(object, ...) {
944 :     -2 * object@glmmll
945 :     })
946 :    
947 : bates 449 setMethod("chol", signature(x = "lmer"),
948 :     function(x, pivot = FALSE, LINPACK = pivot) {
949 :     x@status["factored"] <- FALSE # force a decomposition
950 :     .Call("lmer_factor", x, PACKAGE = "Matrix")
951 :     })
952 :    
953 :     setMethod("solve", signature(a = "lmer", b = "missing"),
954 :     function(a, b, ...)
955 : bates 562 .Call("lmer_invert", a, PACKAGE = "Matrix")
956 : bates 449 )
957 :    
958 :     setMethod("formula", "lmer", function(x, ...) x@call$formula)
959 :    
960 :     setMethod("vcov", signature(object = "lmer"),
961 :     function(object, REML = object@REML, useScale = TRUE,...) {
962 :     sc <- .Call("lmer_sigma", object, REML, PACKAGE = "Matrix")
963 :     rr <- object@RXX
964 :     nms <- object@cnames[[".fixed"]]
965 :     dimnames(rr) <- list(nms, nms)
966 :     nr <- nrow(rr)
967 :     rr <- rr[-nr, -nr, drop = FALSE]
968 :     rr <- rr %*% t(rr)
969 :     if (useScale) {
970 :     rr = sc^2 * rr
971 :     }
972 :     rr
973 :     })
974 :    
975 : bates 550 ## Extract the L matrix
976 :     setAs("lmer", "dtTMatrix",
977 :     function(from)
978 :     {
979 :     ## force a refactorization if the factors have been inverted
980 :     if (from@status["inverted"]) from@status["factored"] <- FALSE
981 :     .Call("lmer_factor", from, PACKAGE = "Matrix")
982 :     L <- lapply(from@L, as, "dgTMatrix")
983 :     nf <- length(from@D)
984 :     Gp <- from@Gp
985 :     nL <- Gp[nf + 1]
986 : bates 562 Li <- integer(0)
987 :     Lj <- integer(0)
988 :     Lx <- double(0)
989 : bates 550 for (i in 1:nf) {
990 :     for (j in 1:i) {
991 :     Lij <- L[[Lind(i, j)]]
992 : bates 562 Li <- c(Li, Lij@i + Gp[i])
993 :     Lj <- c(Lj, Lij@j + Gp[j])
994 :     Lx <- c(Lx, Lij@x)
995 : bates 550 }
996 :     }
997 : bates 562 new("dtTMatrix", Dim = as.integer(c(nL, nL)), i = Li, j = Lj, x = Lx,
998 : bates 550 uplo = "L", diag = "U")
999 :     })
1000 : bates 562
1001 :     ## Extract the ZZX matrix
1002 :     setAs("lmer", "dsTMatrix",
1003 :     function(from)
1004 :     {
1005 :     .Call("lmer_inflate", from, PACKAGE = "Matrix")
1006 :     ZZpO <- lapply(from@ZZpO, as, "dgTMatrix")
1007 :     ZZ <- lapply(from@ZtZ, as, "dgTMatrix")
1008 :     nf <- length(ZZpO)
1009 :     Gp <- from@Gp
1010 :     nZ <- Gp[nf + 1]
1011 :     Zi <- integer(0)
1012 :     Zj <- integer(0)
1013 :     Zx <- double(0)
1014 :     for (i in 1:nf) {
1015 :     ZZpOi <- ZZpO[[i]]
1016 :     Zi <- c(Zi, ZZpOi@i + Gp[i])
1017 :     Zj <- c(Zj, ZZpOi@j + Gp[i])
1018 :     Zx <- c(Zx, ZZpOi@x)
1019 :     if (i > 1) {
1020 :     for (j in 1:(i-1)) {
1021 :     ZZij <- ZZ[[Lind(i, j)]]
1022 :     ## off-diagonal blocks are transposed
1023 :     Zi <- c(Zi, ZZij@j + Gp[j])
1024 :     Zj <- c(Zj, ZZij@i + Gp[i])
1025 :     Zx <- c(Zx, ZZij@x)
1026 :     }
1027 :     }
1028 :     }
1029 :     new("dsTMatrix", Dim = as.integer(c(nZ, nZ)), i = Zi, j = Zj, x = Zx,
1030 :     uplo = "U")
1031 :     })
1032 : bates 689
1033 :     setMethod("fitted", signature(object = "lmer"),
1034 : bates 691 function(object, ...)
1035 :     napredict(attr(object@frame, "na.action"), object@fitted))
1036 : bates 689
1037 :     setMethod("residuals", signature(object = "lmer"),
1038 : bates 691 function(object, ...)
1039 :     naresid(attr(object@frame, "na.action"), object@residuals))
1040 : bates 689
1041 :     setMethod("resid", signature(object = "lmer"),
1042 :     function(object, ...) do.call("residuals", c(list(object), list(...))))
1043 :    
1044 :     setMethod("coef", signature(object = "lmer"),
1045 :     function(object, ...)
1046 :     {
1047 :     fef <- data.frame(rbind(fixef(object)), check.names = FALSE)
1048 :     ref <- as(ranef(object), "list")
1049 :     names(ref) <- names(object@flist)
1050 :     val <- lapply(ref, function(x) fef[rep(1, nrow(x)),])
1051 :     for (i in seq(a = val)) {
1052 :     refi <- ref[[i]]
1053 :     row.names(val[[i]]) <- row.names(refi)
1054 :     if (!all(names(refi) %in% names(fef)))
1055 :     stop("unable to align random and fixed effects")
1056 :     val[[i]][ , names(refi)] <- val[[i]][ , names(refi)] + refi
1057 :     }
1058 :     new("lmer.coef", val)
1059 :     })
1060 :    
1061 :     setMethod("plot", signature(x = "lmer.coef"),
1062 :     function(x, y, ...)
1063 :     {
1064 :     varying <- unique(do.call("c",
1065 :     lapply(x, function(el)
1066 :     names(el)[sapply(el,
1067 :     function(col)
1068 :     any(col != col[1]))])))
1069 :     gf <- do.call("rbind", lapply(x, "[", j = varying))
1070 :     gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
1071 :     switch(min(length(varying), 3),
1072 :     qqmath(eval(substitute(~ x | .grp,
1073 :     list(x = as.name(varying[1])))), gf, ...),
1074 :     xyplot(eval(substitute(y ~ x | .grp,
1075 :     list(y = as.name(varying[1]),
1076 :     x = as.name(varying[2])))), gf, ...),
1077 :     splom(~ gf | .grp, ...))
1078 :     })
1079 :    
1080 :     setMethod("plot", signature(x = "lmer.ranef"),
1081 :     function(x, y, ...)
1082 :     {
1083 :     lapply(x, function(x) {
1084 :     cn <- lapply(colnames(x), as.name)
1085 :     switch(min(ncol(x), 3),
1086 :     qqmath(eval(substitute(~ x, list(x = cn[[1]]))), x, ...),
1087 :     xyplot(eval(substitute(y ~ x, list(y = cn[[1]], x = cn[[2]]))),
1088 :     x, ...),
1089 :     splom(~ x, ...))
1090 :     })
1091 :     })
1092 :    
1093 :     setMethod("with", signature(data = "lmer"),
1094 : bates 690 function(data, expr, ...) {
1095 : bates 691 dat <- eval(data@call$data)
1096 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
1097 :     dat <- dat[-na.act, ]
1098 :     lst <- c(list(. = data), data@flist, data@frame, dat)
1099 :     eval(substitute(expr), lst[unique(names(lst))])
1100 :     })
1101 : bates 690
1102 : bates 691 setMethod("terms", signature(x = "lmer"),
1103 :     function(x, ...) x@terms)

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