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 1127 - (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 : maechler 1127 const <- c(rep.int(FALSE, length(fixInd)),
242 : bates 777 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 : maechler 1127 rep.int(n-p, p)
510 : bates 316 })
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 : maechler 1127 val <- lapply(ref, function(x) fef[rep.int(1, nrow(x)), , drop=FALSE])
764 : bates 689 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 : maechler 1127
775 :     ## maybe wanted:
776 :     ## setMethod("show", signature(object="lmer.coef"),
777 :     ## function(object)
778 :     ## {
779 :     ## })
780 :    
781 : bates 689 setMethod("plot", signature(x = "lmer.coef"),
782 :     function(x, y, ...)
783 :     {
784 : maechler 832 ## require("lattice", quietly = TRUE) -- now via Imports
785 :     varying <- unique(do.call("c",
786 :     lapply(x, function(el)
787 :     names(el)[sapply(el,
788 :     function(col)
789 :     any(col != col[1]))])))
790 :     gf <- do.call("rbind", lapply(x, "[", j = varying))
791 :     gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
792 :     switch(min(length(varying), 3),
793 :     qqmath(eval(substitute(~ x | .grp,
794 :     list(x = as.name(varying[1])))), gf, ...),
795 :     xyplot(eval(substitute(y ~ x | .grp,
796 :     list(y = as.name(varying[1]),
797 :     x = as.name(varying[2])))), gf, ...),
798 :     splom(~ gf | .grp, ...))
799 : bates 689 })
800 :    
801 :     setMethod("plot", signature(x = "lmer.ranef"),
802 :     function(x, y, ...)
803 :     {
804 : maechler 832 ## require("lattice", quietly = TRUE) -- now via Imports
805 :     lapply(x, function(x) {
806 :     cn <- lapply(colnames(x), as.name)
807 :     switch(min(ncol(x), 3),
808 :     qqmath(eval(substitute(~ x, list(x = cn[[1]]))), x, ...),
809 :     xyplot(eval(substitute(y ~ x,
810 :     list(y = cn[[1]],
811 :     x = cn[[2]]))), x, ...),
812 :     splom(~ x, ...))
813 :     })
814 : bates 689 })
815 :    
816 :     setMethod("with", signature(data = "lmer"),
817 : bates 690 function(data, expr, ...) {
818 : bates 691 dat <- eval(data@call$data)
819 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
820 :     dat <- dat[-na.act, ]
821 :     lst <- c(list(. = data), data@flist, data@frame, dat)
822 :     eval(substitute(expr), lst[unique(names(lst))])
823 :     })
824 : bates 690
825 : bates 691 setMethod("terms", signature(x = "lmer"),
826 :     function(x, ...) x@terms)
827 : bates 767
828 :     setMethod("show", signature(object="VarCorr"),
829 :     function(object)
830 :     {
831 :     digits <- max(3, getOption("digits") - 2)
832 :     useScale <- length(object@useScale) > 0 && object@useScale[1]
833 :     sc <- ifelse(useScale, object@scale, 1.)
834 :     reStdDev <- c(lapply(object@reSumry,
835 : maechler 1127 function(x, sc) sc*x@stdDev, sc = sc),
836 :     list(Residual = sc))
837 : bates 767 reLens <- unlist(c(lapply(reStdDev, length)))
838 :     reMat <- array('', c(sum(reLens), 4),
839 : maechler 1127 list(rep.int('', sum(reLens)),
840 : bates 767 c("Groups", "Name", "Variance", "Std.Dev.")))
841 :     reMat[1+cumsum(reLens)-reLens, 1] <- names(reLens)
842 :     reMat[,2] <- c(unlist(lapply(reStdDev, names)), "")
843 :     reMat[,3] <- format(unlist(reStdDev)^2, digits = digits)
844 :     reMat[,4] <- format(unlist(reStdDev), digits = digits)
845 :     if (any(reLens > 1)) {
846 :     maxlen <- max(reLens)
847 :     corr <-
848 :     do.call("rbind",
849 :     lapply(object@reSumry,
850 :     function(x, maxlen) {
851 :     cc <- format(round(x, 3), nsmall = 3)
852 :     cc[!lower.tri(cc)] <- ""
853 :     nr <- dim(cc)[1]
854 :     if (nr >= maxlen) return(cc)
855 :     cbind(cc, matrix("", nr, maxlen-nr))
856 :     }, maxlen))
857 : maechler 1127 colnames(corr) <- c("Corr", rep.int("", maxlen - 1))
858 :     reMat <- cbind(reMat, rbind(corr, rep.int("", ncol(corr))))
859 : bates 767 }
860 :     if (!useScale) reMat <- reMat[-nrow(reMat),]
861 :     print(reMat, quote = FALSE)
862 :     })
863 : bates 769
864 : bates 879 setMethod("mcmcsamp", signature(object = "lmer"),
865 :     function(object, n = 1, verbose = FALSE, saveb = FALSE,
866 : bates 824 trans = TRUE, ...)
867 : bates 820 {
868 : bates 879 if (object@family$family == "gaussian" &&
869 :     object@family$link == "identity") {
870 : bates 861 glmer <- FALSE
871 : bates 879 ans <- .Call("lmer_MCMCsamp", object, saveb, n, trans,
872 : bates 820 PACKAGE = "Matrix")
873 :     } else {
874 : bates 861 glmer <- TRUE
875 :     if (trans)
876 : bates 864 warning("trans option not currently allowed for generalized models")
877 : bates 861 trans <- FALSE
878 : bates 820 ## Check arguments
879 : bates 879 if (length(object@Omega) > 1 || object@nc[1] > 1)
880 : bates 820 stop("mcmcsamp currently defined for glmm models with only one variance component")
881 :     cv <- Matrix:::lmerControl()
882 :     if (verbose) cv$msVerbose <- 1
883 : bates 879 family <- object@family
884 :     frm <- object@frame
885 : bates 810
886 : bates 820 ## recreate model matrices
887 : bates 879 fixed.form <- Matrix:::nobars(object@call$formula)
888 : bates 820 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
889 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
890 :     glm.fit <- glm(eval(fixed.form), family, frm, x = TRUE,
891 :     y = TRUE)
892 :     x <- glm.fit$x
893 :     y <- as.double(glm.fit$y)
894 : bates 879 bars <- Matrix:::findbars(object@call$formula[[3]])
895 : bates 820 random <-
896 :     lapply(bars,
897 :     function(x) list(model.matrix(eval(substitute(~term,
898 :     list(term=x[[2]]))),
899 :     frm),
900 :     eval(substitute(as.factor(fac)[,drop = TRUE],
901 :     list(fac = x[[3]])), frm)))
902 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
903 : bates 879 if (any(names(random) != names(object@flist)))
904 :     random <- random[names(object@flist)]
905 : bates 820 mmats <- c(lapply(random, "[[", 1),
906 :     .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
907 : bates 879 mer <- as(object, "mer")
908 : bates 781
909 : bates 820 ## establish the GS object and the ans matrix
910 : bates 879 eta <- glm.fit$linear.predictors # perhaps later change this to object@fitted?
911 : bates 820 wts <- glm.fit$prior.weights
912 :     wtssqr <- wts * wts
913 :     offset <- glm.fit$offset
914 :     if (is.null(offset)) offset <- numeric(length(eta))
915 :     off <- numeric(length(eta))
916 :     mu <- numeric(length(eta))
917 :     dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
918 :     linkinv <- quote(family$linkinv(eta))
919 :     mu.eta <- quote(family$mu.eta(eta))
920 :     variance <- quote(family$variance(mu))
921 :     LMEopt <- getAnywhere("LMEoptimize<-")
922 :     doLMEopt <- quote(LMEopt(x = mer, value = cv))
923 :     GSpt <- .Call("glmer_init", environment(), PACKAGE = "Matrix")
924 : bates 879 fixed <- object@fixed
925 : bates 820 varc <- .Call("lmer_coef", mer, 2, PACKAGE = "Matrix")
926 :     b <- .Call("lmer_ranef", mer, PACKAGE = "Matrix")
927 : bates 879 ans <- .Call("glmer_MCMCsamp", GSpt, b, fixed, varc, saveb, n,
928 : maechler 832 PACKAGE = "Matrix")
929 : bates 820 .Call("glmer_finalize", GSpt, PACKAGE = "Matrix");
930 :     }
931 : bates 879 gnms <- names(object@flist)
932 :     cnms <- object@cnames
933 :     ff <- fixef(object)
934 : bates 861 colnms <- c(names(ff), if (glmer) character(0) else "sigma^2",
935 : bates 842 unlist(lapply(seq(along = gnms),
936 :     function(i)
937 :     abbrvNms(gnms[i],cnms[[i]]))))
938 :     if (trans) {
939 :     ## parameter type: 0 => fixed effect, 1 => variance,
940 :     ## 2 => covariance
941 : bates 861 ptyp <- c(integer(length(ff)), if (glmer) integer(0) else 1:1,
942 : bates 842 unlist(lapply(seq(along = gnms),
943 :     function(i)
944 :     {
945 :     k <- length(cnms[[i]])
946 :     rep(1:2, c(k, (k*(k-1))/2))
947 :     })))
948 :     colnms[ptyp == 1] <-
949 :     paste("log(", colnms[ptyp == 1], ")", sep = "")
950 :     colnms[ptyp == 2] <-
951 :     paste("atanh(", colnms[ptyp == 2], ")", sep = "")
952 :     }
953 :     colnames(ans) <- colnms
954 : bates 820 ans
955 :     })
956 : bates 781
957 : bates 812 rWishart <- function(n, df, invScal)
958 : bates 1038 .Call("Matrix_rWishart", n, df, invScal, PACKAGE = "Matrix")
959 : bates 820
960 : bates 888
961 :     setMethod("model.matrix", signature(object = "lmer"),
962 :     function(object, ...)
963 : bates 878 {
964 : bates 879 frm <- object@frame
965 :     fixed.form <- Matrix:::nobars(object@call$formula)
966 : bates 878 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
967 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
968 : bates 888 glm.fit <- glm(eval(fixed.form), object@family, frm, x = TRUE, y = TRUE)
969 : bates 879 fxd <- unname(drop(glm.fit$x %*% fixef(object)))
970 : bates 888
971 :     ## Create the random effects model matrices
972 : bates 879 bars <- Matrix:::findbars(object@call$formula[[3]])
973 : bates 878 random <-
974 :     lapply(bars,
975 :     function(x) list(model.matrix(eval(substitute(~term,
976 :     list(term=x[[2]]))),
977 :     frm),
978 :     eval(substitute(as.factor(fac)[,drop = TRUE],
979 :     list(fac = x[[3]])), frm)))
980 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
981 :     ## re-order the random effects pairs if necessary
982 : bates 879 if (any(names(random) != names(object@flist)))
983 :     random <- random[names(object@flist)]
984 : bates 888 c(lapply(random, "[[", 1),
985 :     .fixed = list(cbind(glm.fit$x, .response = glm.fit$y)))
986 :     })
987 :    
988 :     setMethod("simulate", signature(object = "lmer"),
989 : maechler 973 function(object, nsim = 1, seed = NULL, ...)
990 : bates 888 {
991 : maechler 973 if(!exists(".Random.seed", envir = .GlobalEnv))
992 :     runif(1) # initialize the RNG if necessary
993 :     if(is.null(seed))
994 :     RNGstate <- .Random.seed
995 :     else {
996 :     R.seed <- .Random.seed
997 :     set.seed(seed)
998 :     RNGstate <- structure(seed, kind = as.list(RNGkind()))
999 :     on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv))
1000 :     }
1001 : bates 888
1002 :     family <- object@family
1003 :     if (family$family != "gaussian" ||
1004 : maechler 973 family$link != "identity")
1005 : bates 888 stop("simulation of generalized linear mixed models not yet implemented")
1006 :    
1007 :     ## pieces we will need later
1008 :     scale <- .Call("lmer_sigma", object, object@method == "REML",
1009 :     PACKAGE = "Matrix")
1010 :     mmats <- model.matrix(object)
1011 :     ff <- fixef(object)
1012 :    
1013 :     ###_FIXME: If the factor levels have been permuted, has the
1014 :     ### permutation been applied in the stored frame? Otherwise we
1015 :     ### need to check this.
1016 :    
1017 : bates 879 ## similate the linear predictors
1018 : bates 888 lpred <- .Call("lmer_simulate", as(object, "mer"), nsim,
1019 : bates 987 unname(drop(mmats[[length(mmats)]][,seq(a = ff),drop = FALSE] %*% ff)),
1020 : bates 888 mmats, TRUE, PACKAGE = "Matrix")
1021 : bates 879 ## add per-observation noise term
1022 : bates 888 lpred <- as.data.frame(lpred + rnorm(prod(dim(lpred)), sd = scale))
1023 :    
1024 : maechler 973 ## save the seed
1025 :     attr(lpred, "seed") <- RNGstate
1026 : bates 888 lpred
1027 : bates 878 })
1028 : bates 879
1029 :     simulate2 <- function(object, n = 1, ...)
1030 :     {
1031 :     family <- object@family
1032 :     if (family$family != "gaussian" ||
1033 : maechler 973 family$link != "identity")
1034 : bates 879 stop("simulation of generalized linear mixed models not implemented yet")
1035 :    
1036 :     ## create the mean from the fixed effects
1037 :     frm <- object@frame
1038 :     fixed.form <- Matrix:::nobars(object@call$formula)
1039 :     if (inherits(fixed.form, "name")) # RHS is empty - use a constant
1040 :     fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
1041 :     glm.fit <- glm(eval(fixed.form), family, frm, x = TRUE, y = TRUE)
1042 :     lpred <- matrix(glm.fit$x %*% fixef(object), nr = nrow(frm), nc = n)
1043 :    
1044 :     ## Create the random effects model matrices
1045 :     bars <- Matrix:::findbars(object@call$formula[[3]])
1046 :     random <-
1047 :     lapply(bars,
1048 :     function(x) list(model.matrix(eval(substitute(~term,
1049 :     list(term=x[[2]]))),
1050 :     frm),
1051 :     eval(substitute(as.factor(fac)[,drop = TRUE],
1052 :     list(fac = x[[3]])), frm)))
1053 :     names(random) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
1054 :     ## re-order the random effects pairs if necessary
1055 :     flist <- object@flist
1056 :     if (any(names(random) != names(flist)))
1057 :     random <- random[names(flist)]
1058 :     mmats <- lapply(random, "[[", 1)
1059 : maechler 973
1060 : bates 879 ## simulate the random effects
1061 :     scale <- .Call("lmer_sigma", object, object@method == "REML",
1062 :     PACKAGE = "Matrix")
1063 :     Omega <- object@Omega
1064 :     re <- lapply(seq(along = Omega),
1065 :     function(i) {
1066 :     om <- Omega[[i]]
1067 :     nr <- nrow(om)
1068 :     nlev <- length(levels(flist[[i]]))
1069 :     scale * array(solve(chol(new("dpoMatrix", Dim = dim(om),
1070 :     uplo = "U", x = c(om))),
1071 :     matrix(rnorm(nr * n * nlev),
1072 :     nr = nr))@x, c(nr, n, nlev))
1073 :     })
1074 :     ## apply the random effects
1075 :     for (j in seq(along = Omega)) {
1076 :     for (i in 1:nrow(lpred))
1077 :     lpred[i,] <- lpred[i,] + mmats[[j]][i,] %*% re[[j]][, , as.integer(flist[[j]])[i]]
1078 :     }
1079 :     ## add per-observation noise term
1080 :     lpred <- lpred + rnorm(prod(dim(lpred)), sd = scale)
1081 :     attr(lpred, "re") <- re
1082 :     lpred
1083 :     }
1084 :    
1085 :     refdist <- function(fm1, fm2, n, ...)
1086 :     {
1087 : bates 888 cv <- lmerControl()
1088 :     obs <- deviance(fm2) - deviance(fm1)
1089 : bates 879 newy <- simulate(fm2, n)
1090 : bates 888 mm1 <- model.matrix(fm1)
1091 :     mm2 <- model.matrix(fm2)
1092 : bates 879 ref <- numeric(n)
1093 : bates 888 mer1 <- as(fm1, "mer")
1094 :     mer2 <- as(fm2, "mer")
1095 : bates 879 for (j in 1:n) {
1096 : bates 888 .Call("lmer_update_y", mer2, newy[[j]], mm2, PACKAGE = "Matrix")
1097 :     LMEoptimize(mer2) <- cv
1098 :     .Call("lmer_update_y", mer1, newy[[j]], mm1, PACKAGE = "Matrix")
1099 :     LMEoptimize(mer1) <- cv
1100 :     ref[j] <- deviance(mer2) - deviance(mer1)
1101 : bates 879 }
1102 : bates 888 attr(ref, "observed") <- obs
1103 : bates 879 ref
1104 :     }

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