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 1171 - (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 pairs of expressions separated by vertical bars
6 : bates 769 findbars <- function(term)
7 :     {
8 :     if (is.name(term) || is.numeric(term)) return(NULL)
9 :     if (term[[1]] == as.name("(")) return(findbars(term[[2]]))
10 :     if (!is.call(term)) stop("term must be of class call")
11 :     if (term[[1]] == as.name('|')) return(term)
12 :     if (length(term) == 2) return(findbars(term[[2]]))
13 :     c(findbars(term[[2]]), findbars(term[[3]]))
14 :     }
15 :    
16 : bates 775 ## Return the formula omitting the pairs of expressions
17 :     ## that are separated by vertical bars
18 : bates 769 nobars <- function(term)
19 :     {
20 : bates 1150 if (!('|' %in% all.names(term))) return(term)
21 : bates 769 if (is.call(term) && term[[1]] == as.name('|')) return(NULL)
22 :     if (length(term) == 2) {
23 :     nb <- nobars(term[[2]])
24 :     if (is.null(nb)) return(NULL)
25 :     term[[2]] <- nb
26 :     return(term)
27 :     }
28 :     nb2 <- nobars(term[[2]])
29 :     nb3 <- nobars(term[[3]])
30 :     if (is.null(nb2)) return(nb3)
31 :     if (is.null(nb3)) return(nb2)
32 :     term[[2]] <- nb2
33 :     term[[3]] <- nb3
34 :     term
35 :     }
36 :    
37 : bates 775 ## Substitute the '+' function for the '|' function
38 : bates 769 subbars <- function(term)
39 :     {
40 :     if (is.name(term) || is.numeric(term)) return(term)
41 :     if (length(term) == 2) {
42 :     term[[2]] <- subbars(term[[2]])
43 :     return(term)
44 :     }
45 :     stopifnot(length(term) == 3)
46 : maechler 832 if (is.call(term) && term[[1]] == as.name('|'))
47 :     term[[1]] <- as.name('+')
48 : bates 769 term[[2]] <- subbars(term[[2]])
49 :     term[[3]] <- subbars(term[[3]])
50 :     term
51 :     }
52 : bates 824
53 : bates 979 ## Expand an expression with colons to the sum of the lhs
54 :     ## and the current expression
55 :     colExpand <- function(term)
56 :     {
57 :     if (is.name(term) || is.numeric(term)) return(term)
58 :     if (length(term) == 2) {
59 :     term[[2]] <- colExpand(term[[2]])
60 :     return(term)
61 :     }
62 :     stopifnot(length(term) == 3)
63 :     if (is.call(term) && term[[1]] == as.name(':')) {
64 :     return(substitute(A+B, list(A = term, B = colExpand(term[[2]]))))
65 :     }
66 :     term[[2]] <- colExpand(term[[2]])
67 :     term[[3]] <- colExpand(term[[3]])
68 :     term
69 :     }
70 :    
71 : bates 824 abbrvNms <- function(gnm, cnms)
72 :     {
73 :     ans <- paste(abbreviate(gnm), abbreviate(cnms), sep = '.')
74 :     if (length(cnms) > 1) {
75 :     anms <- lapply(cnms, abbreviate, minlength = 3)
76 :     nmmat <- outer(anms, anms, paste, sep = '.')
77 :     ans <- c(ans, paste(abbreviate(gnm, minlength = 3),
78 :     nmmat[upper.tri(nmmat)], sep = '.'))
79 :     }
80 :     ans
81 :     }
82 :    
83 : bates 775 ## Control parameters for lmer
84 :     lmerControl <-
85 : maechler 832 function(maxIter = 200, # used in ../src/lmer.c only
86 : bates 888 tolerance = sqrt(.Machine$double.eps),# ditto
87 : bates 769 msMaxIter = 200,
88 : maechler 832 ## msTol = sqrt(.Machine$double.eps),
89 :     ## FIXME: should be able to pass tolerances to nlminb()
90 :     msVerbose = getOption("verbose"),
91 : bates 752 niterEM = 15,
92 : bates 435 EMverbose = getOption("verbose"),
93 : maechler 843 PQLmaxIt = 30,# FIXME: unused; PQL currently uses 'maxIter' instead
94 : bates 1166 gradient = TRUE,
95 :     Hessian = FALSE # unused _FIXME_
96 : maechler 832 )
97 : bates 435 {
98 : bates 775 list(maxIter = as.integer(maxIter),
99 : maechler 832 tolerance = as.double(tolerance),
100 : bates 775 msMaxIter = as.integer(msMaxIter),
101 : maechler 832 ## msTol = as.double(msTol),
102 :     msVerbose = as.integer(msVerbose),# "integer" on purpose
103 : bates 775 niterEM = as.integer(niterEM),
104 : maechler 832 EMverbose = as.logical(EMverbose),
105 : bates 775 PQLmaxIt = as.integer(PQLmaxIt),
106 : bates 1166 gradient = as.logical(gradient),
107 :     Hessian = as.logical(Hessian))
108 : bates 435 }
109 :    
110 : bates 1166 rWishart <- function(n, df, invScal)
111 :     .Call("Matrix_rWishart", n, df, invScal, PACKAGE = "Matrix")
112 :    
113 :     setMethod("coef", signature(object = "mer"),
114 : bates 1150 function(object, ...)
115 :     {
116 : bates 1166 fef <- data.frame(rbind(fixef(object)), check.names = FALSE)
117 :     ref <- ranef(object)
118 :     val <- lapply(ref, function(x) fef[rep(1, nrow(x)),,drop = FALSE])
119 :     for (i in seq(a = val)) {
120 :     refi <- ref[[i]]
121 :     row.names(val[[i]]) <- row.names(refi)
122 :     nmsi <- colnames(refi)
123 :     if (!all(nmsi %in% names(fef)))
124 :     stop("unable to align random and fixed effects")
125 :     for (nm in nmsi) val[[i]][[nm]] <- val[[i]][[nm]] + refi[,nm]
126 :     }
127 :     val
128 :     })
129 : bates 1150
130 :     ## setMethod("plot", signature(x = "lmer.coef"),
131 :     ## function(x, y, ...)
132 :     ## {
133 :     ## varying <- unique(do.call("c",
134 :     ## lapply(x, function(el)
135 :     ## names(el)[sapply(el,
136 :     ## function(col)
137 :     ## any(col != col[1]))])))
138 :     ## gf <- do.call("rbind", lapply(x, "[", j = varying))
139 :     ## gf$.grp <- factor(rep(names(x), sapply(x, nrow)))
140 :     ## switch(min(length(varying), 3),
141 :     ## qqmath(eval(substitute(~ x | .grp,
142 :     ## list(x = as.name(varying[1])))), gf, ...),
143 :     ## xyplot(eval(substitute(y ~ x | .grp,
144 :     ## list(y = as.name(varying[1]),
145 :     ## x = as.name(varying[2])))), gf, ...),
146 :     ## splom(~ gf | .grp, ...))
147 :     ## })
148 :    
149 : bates 1166 setMethod("plot", signature(x = "lmer.ranef"),
150 :     function(x, y, ...)
151 :     {
152 :     lapply(x, function(x) {
153 :     cn <- lapply(colnames(x), as.name)
154 :     switch(min(ncol(x), 3),
155 :     qqmath(eval(substitute(~ x, list(x = cn[[1]]))), x, ...),
156 :     xyplot(eval(substitute(y ~ x,
157 :     list(y = cn[[1]],
158 :     x = cn[[2]]))), x, ...),
159 :     splom(~ x, ...))
160 :     })
161 :     })
162 : bates 1150
163 :     setMethod("with", signature(data = "lmer"),
164 :     function(data, expr, ...) {
165 :     dat <- eval(data@call$data)
166 :     if (!is.null(na.act <- attr(data@frame, "na.action")))
167 :     dat <- dat[-na.act, ]
168 :     lst <- c(list(. = data), data@flist, data@frame, dat)
169 :     eval(substitute(expr), lst[unique(names(lst))])
170 :     })
171 :    
172 :     setMethod("terms", signature(x = "lmer"),
173 :     function(x, ...) x@terms)
174 :    
175 :    
176 : bates 755 setMethod("lmer", signature(formula = "formula"),
177 : bates 689 function(formula, data, family,
178 :     method = c("REML", "ML", "PQL", "Laplace", "AGQ"),
179 : bates 901 control = list(), start,
180 : bates 435 subset, weights, na.action, offset,
181 : maechler 832 model = TRUE, x = FALSE, y = FALSE , ...)
182 :     {
183 :     ## match and check parameters
184 : bates 755 if (length(formula) < 3) stop("formula must be a two-sided formula")
185 :     cv <- do.call("lmerControl", control)
186 : bates 1150
187 :     ## Must evaluate the model frame first and then fit the glm using
188 :     ## that frame. Otherwise missing values in the grouping factors
189 :     ## cause inconsistent numbers of observations.
190 : maechler 832 mf <- match.call()
191 : bates 755 m <- match(c("family", "data", "subset", "weights",
192 :     "na.action", "offset"), names(mf), 0)
193 : bates 1150 mf <- fe <- mf[c(1, m)]
194 : bates 755 frame.form <- subbars(formula) # substitute `+' for `|'
195 :     fixed.form <- nobars(formula) # remove any terms with `|'
196 : bates 767 if (inherits(fixed.form, "name")) # RHS is empty - use a constant
197 : bates 755 fixed.form <- substitute(foo ~ 1, list(foo = fixed.form))
198 :     environment(fixed.form) <- environment(frame.form) <- environment(formula)
199 : bates 1150
200 :     ## evaluate a model frame for fixed and random effects
201 :     mf$formula <- frame.form
202 :     mf$family <- NULL
203 :     mf$drop.unused.levels <- TRUE
204 :     mf[[1]] <- as.name("model.frame")
205 :     frm <- eval(mf, parent.frame())
206 :    
207 :     ## fit a glm model to the fixed formula
208 :     fe$formula <- fixed.form
209 :     fe$subset <- NULL # subset has already been created in call to data.frame
210 :     fe$data <- frm
211 :     fe$x <- fe$model <- fe$y <- TRUE
212 :     fe[[1]] <- as.name("glm")
213 :     glm.fit <- eval(fe, parent.frame())
214 : bates 767 x <- glm.fit$x
215 :     y <- as.double(glm.fit$y)
216 : bates 769 family <- glm.fit$family
217 : bates 1150
218 : bates 939 ## check for a linear mixed model
219 :     lmm <- family$family == "gaussian" && family$link == "identity"
220 : maechler 832 if (lmm) { # linear mixed model
221 :     method <- match.arg(method)
222 :     if (method %in% c("PQL", "Laplace", "AGQ")) {
223 :     warning(paste('Argument method = "', method,
224 :     '" is not meaningful for a linear mixed model.\n',
225 :     'Using method = "REML".\n', sep = ''))
226 :     method <- "REML"
227 :     }
228 :     } else { # generalized linear mixed model
229 :     if (missing(method)) method <- "PQL"
230 :     else {
231 :     method <- match.arg(method)
232 :     if (method == "ML") method <- "PQL"
233 :     if (method == "REML")
234 :     warning('Argument method = "REML" is not meaningful ',
235 :     'for a generalized linear mixed model.',
236 :     '\nUsing method = "PQL".\n')
237 :     }
238 :     }
239 : bates 1166 if (method == "AGQ")
240 :     stop('method = "AGQ" not yet implemented for supernodal representation')
241 : bates 1150 ## create factor list for the random effects
242 : bates 435 bars <- findbars(formula[[3]])
243 : bates 1150 names(bars) <- unlist(lapply(bars, function(x) deparse(x[[3]])))
244 :     fl <- lapply(bars,
245 :     function(x)
246 :     eval(substitute(as.factor(fac)[,drop = TRUE],
247 :     list(fac = x[[3]])), frm))
248 : bates 435 ## order factor list by decreasing number of levels
249 : bates 1150 nlev <- sapply(fl, function(x) length(levels(x)))
250 : bates 452 if (any(diff(nlev) > 0)) {
251 : bates 1150 ord <- rev(order(nlev))
252 :     bars <- bars[ord]
253 :     fl <- fl[ord]
254 : bates 435 }
255 : bates 1150 ## create list of transposed model matrices for random effects
256 :     Ztl <- lapply(bars, function(x)
257 :     t(model.matrix(eval(substitute(~ expr,
258 :     list(expr = x[[2]]))),
259 :     frm)))
260 :     ## Create the mixed-effects representation (mer) object
261 :     mer <- .Call("mer_create", fl,
262 :     .Call("Zt_create", fl, Ztl, PACKAGE = "Matrix"),
263 :     x, y, method, sapply(Ztl, nrow),
264 :     c(lapply(Ztl, rownames), list(.fixed = colnames(x))),
265 :     !(family$family %in% c("binomial", "poisson")),
266 :     match.call(), family,
267 :     PACKAGE = "Matrix")
268 :     if (lmm) {
269 :     .Call("mer_ECMEsteps", mer, cv$niterEM, cv$EMverbose, PACKAGE = "Matrix")
270 : bates 755 LMEoptimize(mer) <- cv
271 : bates 1166 return(new("lmer", mer,
272 :     frame = if (model) frm else data.frame(),
273 :     terms = glm.fit$terms))
274 : bates 755 }
275 :    
276 :     ## The rest of the function applies to generalized linear mixed models
277 :     gVerb <- getOption("verbose")
278 : bates 776 eta <- glm.fit$linear.predictors
279 : bates 767 wts <- glm.fit$prior.weights
280 : bates 774 wtssqr <- wts * wts
281 : bates 767 offset <- glm.fit$offset
282 :     if (is.null(offset)) offset <- numeric(length(eta))
283 :     linkinv <- quote(family$linkinv(eta))
284 :     mu.eta <- quote(family$mu.eta(eta))
285 : bates 1150 mu <- family$linkinv(eta)
286 : bates 767 variance <- quote(family$variance(mu))
287 : bates 1150 dev.resids <- quote(family$dev.resids(y, mu, wtssqr))
288 : bates 775 LMEopt <- get("LMEoptimize<-")
289 :     doLMEopt <- quote(LMEopt(x = mer, value = cv))
290 : bates 767
291 : bates 809 GSpt <- .Call("glmer_init", environment(), PACKAGE = "Matrix")
292 :     .Call("glmer_PQL", GSpt, PACKAGE = "Matrix") # obtain PQL estimates
293 : bates 1166 PQLpars <- c(fixef(mer),
294 :     .Call("mer_coef", mer, 2, PACKAGE = "Matrix"))
295 :     if (method == "PQL") {
296 :     .Call("glmer_devLaplace", PQLpars, GSpt, PACKAGE = "Matrix")
297 :     .Call("glmer_finalize", GSpt, PACKAGE = "Matrix")
298 :     return(new("lmer", mer,
299 :     frame = if (model) frm else data.frame(),
300 :     terms = glm.fit$terms))
301 :     }
302 :    
303 : bates 774 fixInd <- seq(ncol(x))
304 :     ## pars[fixInd] == beta, pars[-fixInd] == theta
305 : bates 777 ## indicator of constrained parameters
306 : bates 1150 const <- c(rep(FALSE, length(fixInd)),
307 :     unlist(lapply(mer@nc[seq(along = fl)],
308 : bates 777 function(k) 1:((k*(k+1))/2) <= k)
309 :     ))
310 : bates 1150 devLaplace <- function(pars)
311 :     .Call("glmer_devLaplace", pars, GSpt, PACKAGE = "Matrix")
312 : maechler 832
313 : bates 1150 optimRes <-
314 :     nlminb(PQLpars, devLaplace,
315 :     lower = ifelse(const, 5e-10, -Inf),
316 : bates 1166 control = list(trace = cv$msVerbose,
317 : bates 1150 iter.max = cv$msMaxIter))
318 :     .Call("glmer_finalize", GSpt, PACKAGE = "Matrix")
319 : bates 1166 return(new("lmer", mer,
320 :     frame = if (model) frm else data.frame(),
321 :     terms = glm.fit$terms))
322 : bates 1150
323 : bates 435 })
324 :    
325 : bates 1150 ## Extract the L matrix
326 :     setAs("mer", "dtCMatrix", function(from)
327 :     .Call("mer_dtCMatrix", from, PACKAGE = "Matrix"))
328 :    
329 :     ## Extract the fixed effects
330 :     setMethod("fixef", signature(object = "mer"),
331 :     function(object, ...)
332 :     .Call("mer_fixef", object, PACKAGE = "Matrix"))
333 :    
334 :     ## Extract the random effects
335 :     setMethod("ranef", signature(object = "mer"),
336 :     function(object, ...)
337 : bates 1166 new("lmer.ranef", .Call("mer_ranef", object, PACKAGE = "Matrix"))
338 : bates 1150 )
339 :    
340 :     ## Optimization for mer objects
341 : bates 755 setReplaceMethod("LMEoptimize", signature(x="mer", value="list"),
342 : bates 316 function(x, value)
343 :     {
344 :     if (value$msMaxIter < 1) return(x)
345 :     nc <- x@nc
346 : bates 1150 constr <- unlist(lapply(nc, function(k) 1:((k*(k+1))/2) <= k))
347 : bates 752 fn <- function(pars)
348 : bates 1150 deviance(.Call("mer_coefGets", x, pars, 2, PACKAGE = "Matrix"))
349 : bates 1166 gr <- if (value$gradient)
350 : bates 1150 function(pars) {
351 :     if (!isTRUE(all.equal(pars,
352 :     .Call("mer_coef", x,
353 :     2, PACKAGE = "Matrix"))))
354 :     .Call("mer_coefGets", x, pars, 2, PACKAGE = "Matrix")
355 :     .Call("mer_gradient", x, 2, PACKAGE = "Matrix")
356 :     }
357 :     else NULL
358 :     optimRes <- nlminb(.Call("mer_coef", x, 2, PACKAGE = "Matrix"),
359 :     fn, gr,
360 :     lower = ifelse(constr, 5e-10, -Inf),
361 :     control = list(iter.max = value$msMaxIter,
362 :     trace = as.integer(value$msVerbose)))
363 :     .Call("mer_coefGets", x, optimRes$par, 2, PACKAGE = "Matrix")
364 : bates 316 if (optimRes$convergence != 0) {
365 : bates 1150 warning(paste("nlminb returned message",
366 : bates 777 optimRes$message,"\n"))
367 : bates 316 }
368 :     return(x)
369 :     })
370 :    
371 : bates 1150 setMethod("deviance", signature(object = "mer"),
372 :     function(object, ...) {
373 :     .Call("mer_factor", object, PACKAGE = "Matrix")
374 :     object@deviance[[ifelse(object@method == "REML", "REML", "ML")]]
375 : bates 316 })
376 :    
377 : bates 1150 setMethod("mcmcsamp", signature(object = "mer"),
378 :     function(object, n = 1, verbose = FALSE, saveb = FALSE,
379 :     trans = TRUE, ...)
380 :     {
381 : bates 1171 family <- object@family
382 : bates 1170 lmm <- family$family == "gaussian" && family$link == "identity"
383 :     if (!lmm)
384 :     stop("mcmcsamp for GLMMs not yet implemented in supernodal representation")
385 : bates 1150 ans <- t(.Call("mer_MCMCsamp", object, saveb, n,
386 :     trans, PACKAGE = "Matrix"))
387 :     attr(ans, "mcpar") <- as.integer(c(1, n, 1))
388 :     class(ans) <- "mcmc"
389 :     glmer <- FALSE
390 :     gnms <- names(object@flist)
391 :     cnms <- object@cnames
392 :     ff <- fixef(object)
393 :     colnms <- c(names(ff), if (glmer) character(0) else "sigma^2",
394 :     unlist(lapply(seq(along = gnms),
395 :     function(i)
396 :     abbrvNms(gnms[i],cnms[[i]]))))
397 :     if (trans) {
398 :     ## parameter type: 0 => fixed effect, 1 => variance,
399 :     ## 2 => covariance
400 :     ptyp <- c(integer(length(ff)), if (glmer) integer(0) else 1:1,
401 :     unlist(lapply(seq(along = gnms),
402 :     function(i)
403 :     {
404 :     k <- length(cnms[[i]])
405 :     rep(1:2, c(k, (k*(k-1))/2))
406 :     })))
407 :     colnms[ptyp == 1] <-
408 :     paste("log(", colnms[ptyp == 1], ")", sep = "")
409 :     colnms[ptyp == 2] <-
410 :     paste("atanh(", colnms[ptyp == 2], ")", sep = "")
411 :     }
412 :     colnames(ans) <- colnms
413 :     ans
414 :     })
415 : bates 316
416 : bates 1150 setMethod("simulate", signature(object = "mer"),
417 :     function(object, nsim = 1, seed = NULL, ...)
418 :     {
419 :     if(!exists(".Random.seed", envir = .GlobalEnv))
420 :     runif(1) # initialize the RNG if necessary
421 :     if(is.null(seed))
422 :     RNGstate <- .Random.seed
423 :     else {
424 :     R.seed <- .Random.seed
425 :     set.seed(seed)
426 :     RNGstate <- structure(seed, kind = as.list(RNGkind()))
427 :     on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv))
428 :     }
429 : deepayan 721
430 : bates 1150 family <- object@family
431 :     if (family$family != "gaussian" ||
432 :     family$link != "identity")
433 :     stop("simulation of generalized linear mixed models not yet implemented")
434 :     ## similate the linear predictors
435 :     lpred <- .Call("mer_simulate", object, nsim, PACKAGE = "Matrix")
436 :     sc <- 1
437 : maechler 1165 if (object@useScale)
438 : bates 1150 sc <- .Call("mer_sigma", object, object@method == "REML",
439 :     PACKAGE = "Matrix")
440 :     ## add fixed-effects contribution and per-observation noise term
441 :     lpred <- as.data.frame(lpred + drop(object@X %*% fixef(object)) +
442 :     rnorm(prod(dim(lpred)), sd = sc))
443 :     ## save the seed
444 :     attr(lpred, "seed") <- RNGstate
445 :     lpred
446 :     })
447 : bates 316
448 :    
449 : bates 1150 setMethod("show", "mer",
450 : bates 316 function(object) {
451 : bates 1150 vcShow <- function(varc, useScale)
452 :     {
453 :     digits <- max(3, getOption("digits") - 2)
454 :     sc <- attr(varc, "sc")
455 :     recorr <- lapply(varc, function(el) el@factors$correlation)
456 :     reStdDev <- c(lapply(recorr, slot, "sd"), list(Residual = sc))
457 :     reLens <- unlist(c(lapply(reStdDev, length)))
458 :     reMat <- array('', c(sum(reLens), 4),
459 :     list(rep('', sum(reLens)),
460 :     c("Groups", "Name", "Variance", "Std.Dev.")))
461 :     reMat[1+cumsum(reLens)-reLens, 1] <- names(reLens)
462 :     reMat[,2] <- c(unlist(lapply(reStdDev, names)), "")
463 :     reMat[,3] <- format(unlist(reStdDev)^2, digits = digits)
464 :     reMat[,4] <- format(unlist(reStdDev), digits = digits)
465 :     if (any(reLens > 1)) {
466 :     maxlen <- max(reLens)
467 :     corr <-
468 :     do.call("rbind",
469 :     lapply(recorr,
470 :     function(x, maxlen) {
471 :     x <- as(x, "matrix")
472 :     cc <- format(round(x, 3), nsmall = 3)
473 :     cc[!lower.tri(cc)] <- ""
474 :     nr <- dim(cc)[1]
475 :     if (nr >= maxlen) return(cc)
476 :     cbind(cc, matrix("", nr, maxlen-nr))
477 :     }, maxlen))
478 :     colnames(corr) <- c("Corr", rep("", maxlen - 1))
479 :     reMat <- cbind(reMat, rbind(corr, rep("", ncol(corr))))
480 :     }
481 :     if (!useScale) reMat <- reMat[-nrow(reMat),]
482 :     print(reMat, quote = FALSE)
483 :     }
484 : maechler 1165
485 : bates 1150 fcoef <- .Call("mer_fixef", object, PACKAGE = "Matrix")
486 : bates 449 useScale <- object@useScale
487 : bates 1150 corF <- vcov(object)@factors$correlation
488 : bates 1166 #DF <- getFixDF(object)
489 :     coefs <- cbind(fcoef, corF@sd)#, DF)
490 : bates 316 dimnames(coefs) <-
491 : bates 1166 list(names(fcoef), c("Estimate", "Std. Error"))#, "DF"))
492 : bates 1123 digits <- max(3, getOption("digits") - 2)
493 : bates 755 REML <- object@method == "REML"
494 : bates 1150 llik <- logLik(object, REML)
495 : bates 449 dev <- object@deviance
496 : bates 1150 devc <- object@devComp
497 : maechler 1165
498 : bates 449 rdig <- 5
499 : bates 727 if (glz <- !(object@method %in% c("REML", "ML"))) {
500 :     cat(paste("Generalized linear mixed model fit using",
501 :     object@method, "\n"))
502 :     } else {
503 :     cat("Linear mixed-effects model fit by ")
504 : bates 755 cat(if(REML) "REML\n" else "maximum likelihood\n")
505 : bates 727 }
506 : bates 449 if (!is.null(object@call$formula)) {
507 :     cat("Formula:", deparse(object@call$formula),"\n")
508 :     }
509 :     if (!is.null(object@call$data)) {
510 :     cat(" Data:", deparse(object@call$data), "\n")
511 :     }
512 :     if (!is.null(object@call$subset)) {
513 :     cat(" Subset:",
514 :     deparse(asOneSidedFormula(object@call$subset)[[2]]),"\n")
515 :     }
516 : bates 727 if (glz) {
517 : bates 750 cat(" Family: ", object@family$family, "(",
518 :     object@family$link, " link)\n", sep = "")
519 : bates 727 print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
520 : bates 1150 logLik = c(llik),
521 :     deviance = -2*llik,
522 :     row.names = ""))
523 : bates 727 } else {
524 :     print(data.frame(AIC = AIC(llik), BIC = BIC(llik),
525 : bates 1150 logLik = c(llik),
526 :     MLdeviance = dev["ML"],
527 :     REMLdeviance = dev["REML"],
528 :     row.names = ""))
529 : bates 727 }
530 : bates 449 cat("Random effects:\n")
531 : bates 1150 vcShow(VarCorr(object), useScale)
532 : bates 449 ngrps <- lapply(object@flist, function(x) length(levels(x)))
533 : bates 1150 cat(sprintf("# of obs: %d, groups: ", devc[1]))
534 : bates 449 cat(paste(paste(names(ngrps), ngrps, sep = ", "), collapse = "; "))
535 :     cat("\n")
536 :     if (!useScale)
537 :     cat("\nEstimated scale (compare to 1) ",
538 : bates 1150 .Call("mer_sigma", object, FALSE, PACKAGE = "Matrix"),
539 : bates 449 "\n")
540 :     if (nrow(coefs) > 0) {
541 : bates 1150 if (useScale) {
542 :     stat <- coefs[,1]/coefs[,2]
543 : bates 1166 #pval <- 2*pt(abs(stat), coefs[,3], lower = FALSE)
544 : bates 1150 nms <- colnames(coefs)
545 : bates 1166 coefs <- cbind(coefs, stat) #, pval)
546 :     colnames(coefs) <- c(nms, "t value")#, "Pr(>|t|)")
547 : bates 1150 } else {
548 :     coefs <- coefs[, 1:2, drop = FALSE]
549 :     stat <- coefs[,1]/coefs[,2]
550 :     pval <- 2*pnorm(abs(stat), lower = FALSE)
551 :     nms <- colnames(coefs)
552 :     coefs <- cbind(coefs, stat, pval)
553 :     colnames(coefs) <- c(nms, "z value", "Pr(>|z|)")
554 : bates 449 }
555 :     cat("\nFixed effects:\n")
556 : bates 1166 printCoefmat(coefs, zap.ind = 3)#, tst.ind = 4)
557 : bates 1150 rn <- rownames(coefs)
558 :     if (!is.null(corF)) {
559 :     p <- ncol(corF)
560 :     if (p > 1) {
561 :     cat("\nCorrelation of Fixed Effects:\n")
562 :     corF <- matrix(format(round(corF@x, 3), nsmall = 3),
563 :     nc = p)
564 :     dimnames(corF) <- list(
565 :     abbreviate(rn, minlen=11),
566 :     abbreviate(rn, minlen=6))
567 :     corF[!lower.tri(corF)] <- ""
568 :     print(corF[-1, -p, drop=FALSE], quote = FALSE)
569 : bates 449 }
570 :     }
571 :     }
572 :     invisible(object)
573 : bates 316 })
574 :    
575 : bates 1150 setMethod("vcov", signature(object = "mer"),
576 :     function(object, REML = object@method == "REML",
577 :     useScale = object@useScale,...) {
578 :     sc <- if (object@useScale) {
579 :     .Call("mer_sigma", object, REML, PACKAGE = "Matrix")
580 :     } else { 1 }
581 :     rr <- as(sc^2 * tcrossprod(solve(object@RXX)), "dpoMatrix")
582 :     rr@factors$correlation <- as(rr, "correlation")
583 :     rr
584 :     })
585 :    
586 : bates 316 ## calculates degrees of freedom for fixed effects Wald tests
587 :     ## This is a placeholder. The answers are generally wrong. It will
588 :     ## be very tricky to decide what a 'right' answer should be with
589 :     ## crossed random effects.
590 :    
591 : bates 1150 setMethod("getFixDF", signature(object="mer"),
592 :     function(object, ...) {
593 :     devc <- object@devComp
594 :     rep(as.integer(devc[1]- devc[2]), devc[2])
595 :     })
596 : bates 316
597 : bates 755 setMethod("logLik", signature(object="mer"),
598 :     function(object, REML = object@method == "REML", ...) {
599 : bates 446 val <- -deviance(object, REML = REML)/2
600 : bates 1150 devc <- as.integer(object@devComp[1:2])
601 :     attr(val, "nall") <- attr(val, "nobs") <- devc[1]
602 :     attr(val, "df") <- abs(devc[2]) +
603 :     length(.Call("mer_coef", object, 0, PACKAGE = "Matrix"))
604 : maechler 832 attr(val, "REML") <- REML
605 : bates 446 class(val) <- "logLik"
606 :     val
607 :     })
608 :    
609 : bates 1150 setMethod("VarCorr", signature(x = "mer"),
610 :     function(x, REML = x@method == "REML", useScale = x@useScale, ...)
611 :     {
612 :     sc <- 1
613 :     if (useScale)
614 :     sc <- .Call("mer_sigma", x, REML, PACKAGE = "Matrix")
615 :     sc2 <- sc * sc
616 : bates 1168 cnames <- x@cnames
617 :     ans <- x@Omega
618 :     for (i in seq(a=ans)) {
619 :     el <- as(sc2 * solve(ans[[i]]), "dpoMatrix")
620 :     el@Dimnames <- list(cnames[[i]], cnames[[i]])
621 : bates 1150 el@factors$correlation <- as(el, "correlation")
622 : bates 1168 ans[[i]] <- el
623 :     }
624 : bates 1150 attr(ans, "sc") <- sc
625 :     ans
626 :     })
627 : deepayan 721
628 : bates 1150 setMethod("anova", signature(object = "mer"),
629 : bates 446 function(object, ...)
630 :     {
631 :     mCall <- match.call(expand.dots = TRUE)
632 :     dots <- list(...)
633 :     modp <- logical(0)
634 :     if (length(dots))
635 : bates 1166 modp <- sapply(dots, is, "mer") | sapply(dots, is, "lm")
636 : bates 446 if (any(modp)) { # multiple models - form table
637 :     opts <- dots[!modp]
638 :     mods <- c(list(object), dots[modp])
639 :     names(mods) <- sapply(as.list(mCall)[c(FALSE, TRUE, modp)], as.character)
640 :     mods <- mods[order(sapply(lapply(mods, logLik, REML = FALSE), attr, "df"))]
641 :     calls <- lapply(mods, slot, "call")
642 :     data <- lapply(calls, "[[", "data")
643 :     if (any(data != data[[1]])) stop("all models must be fit to the same data object")
644 :     header <- paste("Data:", data[[1]])
645 :     subset <- lapply(calls, "[[", "subset")
646 :     if (any(subset != subset[[1]])) stop("all models must use the same subset")
647 :     if (!is.null(subset[[1]]))
648 :     header <-
649 :     c(header, paste("Subset", deparse(subset[[1]]), sep = ": "))
650 :     llks <- lapply(mods, logLik, REML = FALSE)
651 :     Df <- sapply(llks, attr, "df")
652 :     llk <- unlist(llks)
653 :     chisq <- 2 * pmax(0, c(NA, diff(llk)))
654 :     dfChisq <- c(NA, diff(Df))
655 :     val <- data.frame(Df = Df,
656 :     AIC = sapply(llks, AIC),
657 :     BIC = sapply(llks, BIC),
658 :     logLik = llk,
659 :     "Chisq" = chisq,
660 :     "Chi Df" = dfChisq,
661 :     "Pr(>Chisq)" = pchisq(chisq, dfChisq, lower = FALSE),
662 :     check.names = FALSE)
663 :     class(val) <- c("anova", class(val))
664 :     attr(val, "heading") <-
665 : bates 690 c(header, "Models:",
666 : bates 446 paste(names(mods),
667 :     unlist(lapply(lapply(calls, "[[", "formula"), deparse)),
668 : bates 690 sep = ": "))
669 : bates 446 return(val)
670 :     } else {
671 : bates 571 foo <- object
672 : bates 1166 #foo@status["factored"] <- FALSE
673 :     #.Call("mer_factor", foo, PACKAGE="Matrix")
674 :     #dfr <- getFixDF(foo)
675 : bates 1150 ss <- foo@rXy^2
676 :     ssr <- exp(foo@devComp["logryy2"])
677 : bates 1166 names(ss) <- object@cnames[[".fixed"]]
678 :     asgn <- attr(foo@X, "assign")
679 : bates 571 terms <- foo@terms
680 :     nmeffects <- attr(terms, "term.labels")
681 :     if ("(Intercept)" %in% names(ss))
682 :     nmeffects <- c("(Intercept)", nmeffects)
683 :     ss <- unlist(lapply(split(ss, asgn), sum))
684 :     df <- unlist(lapply(split(asgn, asgn), length))
685 : bates 1123 #dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
686 : bates 571 ms <- ss/df
687 : bates 1123 #f <- ms/(ssr/dfr)
688 :     #P <- pf(f, df, dfr, lower.tail = FALSE)
689 :     #table <- data.frame(df, ss, ms, dfr, f, P)
690 :     table <- data.frame(df, ss, ms)
691 : bates 571 dimnames(table) <-
692 :     list(nmeffects,
693 : bates 1123 # c("Df", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
694 :     c("Df", "Sum Sq", "Mean Sq"))
695 : bates 1166 if ("(Intercept)" %in% nmeffects) table <- table[-match("(Intercept)", nmeffects), ]
696 : bates 571 attr(table, "heading") <- "Analysis of Variance Table"
697 :     class(table) <- c("anova", "data.frame")
698 :     table
699 : bates 446 }
700 : bates 316 })
701 : bates 446
702 : bates 1150 setMethod("confint", signature(object = "mer"),
703 :     function(object, parm, level = 0.95, ...)
704 : maechler 1165 .NotYetImplemented()
705 : bates 1150 )
706 : bates 446
707 : bates 1150 setMethod("fitted", signature(object = "mer"),
708 :     function(object, ...)
709 : bates 1162 .Call("mer_fitted", object, PACKAGE = "Matrix")
710 : bates 1123 )
711 : bates 446
712 : bates 1150 setMethod("formula", signature(x = "mer"),
713 :     function(x, ...)
714 :     x@call$formula
715 : bates 449 )
716 :    
717 : bates 1150 setMethod("residuals", signature(object = "mer"),
718 : bates 691 function(object, ...)
719 : maechler 1165 .NotYetImplemented()
720 : bates 1150 )
721 : bates 689
722 : bates 1150 setMethod("resid", signature(object = "mer"),
723 : bates 691 function(object, ...)
724 : maechler 1165 .NotYetImplemented()
725 : bates 1150 )
726 : bates 689
727 : bates 1150 setMethod("summary", signature(object = "mer"),
728 : bates 1166 function(object, ...) object
729 : bates 1150 )
730 : bates 689
731 : bates 1150 setMethod("update", signature(object = "mer"),
732 : bates 888 function(object, ...)
733 : maechler 1165 .NotYetImplemented()
734 : bates 1150 )
735 : bates 888
736 :    
737 : bates 1150 simss <- function(fm0, fma, nsim)
738 : bates 879 {
739 : bates 1150 ysim <- simulate(fm0, nsim)
740 : bates 1166 cv <- list(gradient = FALSE, msMaxIter = 200:200,
741 : bates 1150 msVerbose = 0:0)
742 :     sapply(ysim, function(yy) {
743 :     .Call("mer_update_y", fm0, yy, PACKAGE = "Matrix")
744 :     LMEoptimize(fm0) <- cv
745 :     .Call("mer_update_y", fma, yy, PACKAGE = "Matrix")
746 :     LMEoptimize(fma) <- cv
747 :     exp(c(H0 = fm0@devComp[["logryy2"]],
748 :     Ha = fma@devComp[["logryy2"]]))
749 :     })
750 : bates 879 }
751 : bates 1166
752 :     ## Some leftover code from the old AGQ method in lmer.
753 :     if (FALSE) {
754 :     ### FIXME: For nf == 1 change this to an AGQ evaluation. Needs
755 :     ### AGQ for nc > 1 first.
756 :     fxd <- PQLpars[fixInd]
757 :     loglik <- logLik(mer)
758 :    
759 :     if (method %in% c("Laplace", "AGQ")) {
760 :     nAGQ <- 1
761 :     if (method == "AGQ") { # determine nAGQ at PQL estimates
762 :     dev11 <- devAGQ(PQLpars, 11)
763 :     ## FIXME: Should this be an absolute or a relative tolerance?
764 :     devTol <- sqrt(.Machine$double.eps) * abs(dev11)
765 :     for (nAGQ in c(9, 7, 5, 3, 1))
766 :     if (abs(dev11 - devAGQ(PQLpars, nAGQ - 2)) > devTol) break
767 :     nAGQ <- nAGQ + 2
768 :     if (gVerb)
769 :     cat(paste("Using", nAGQ, "quadrature points per column\n"))
770 :     }
771 :     obj <- function(pars)
772 :     .Call("glmer_devAGQ", pars, GSpt, nAGQ, PACKAGE = "Matrix")
773 :     optimRes <-
774 :     nlminb(PQLpars, obj,
775 :     lower = ifelse(const, 5e-10, -Inf),
776 :     control = list(trace = getOption("verbose"),
777 :     iter.max = cv$msMaxIter))
778 :     optpars <- optimRes$par
779 :     if (optimRes$convergence != 0)
780 :     warning("nlminb failed to converge")
781 :     deviance <- optimRes$objective
782 :     if (gVerb)
783 :     cat(paste("convergence message", optimRes$message, "\n"))
784 :     fxd[] <- optpars[fixInd] ## preserve the names
785 :     .Call("lmer_coefGets", mer, optpars[-fixInd], 2, PACKAGE = "Matrix")
786 :     }
787 :    
788 :     .Call("glmer_finalize", GSpt, PACKAGE = "Matrix")
789 :     loglik[] <- -deviance/2
790 :     }

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