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

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

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