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

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