File: methods.R

package info (click to toggle)
lme4 2.0-1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,860 kB
  • sloc: cpp: 2,543; makefile: 2
file content (301 lines) | stat: -rw-r--r-- 10,884 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
influence.merMod <- function(model, groups, data, maxfun=1000, do.coef = TRUE,
                             start=NULL,
                             parallel = c("no", "multicore", "snow"),
                             ncpus = getOption("influence.ncpus", 1L),
                             cl = NULL,
                             ncores,
                             ...) {

    if (!missing(ncores)) {
        .Deprecated(msg = "argument 'ncores' is deprecated; please use 'parallel', 'ncpus', and 'cl' instead")
        ncpus <- ncores
        parallel <- "snow"
    }

    parallel <- match.arg(parallel)

    # (parallel, ncpus, cl) -> (parallel)
    eval(initialize.parallel)

    .groups <- NULL  ## avoid false-positive code checks
    .vcov <- function(x) Matrix::as.matrix(vcov(x))

    if (...length()>0) warning("disregarded additional arguments")
    if (!do.coef) {
        ## simple/quick/trivial results
        result <- list(hat=hatvalues(model))
        class(result) <- "influence.merMod"
        return(result)
    }
    if (missing(data)) {
        data <- getCall(model)$data
        data <- if (!is.null(data)) eval(data, parent.frame())
                else stop("model did not use the data argument")
    }
    data <- as.data.frame(data) ## prevent tibble trouble
    if (missing(groups)) {
        groups <- ".case"
        data$.case <- rownames(data)
    }
    else if (length(groups) > 1){
        del.var <- paste0(groups, collapse=".")
        data[, del.var] <- apply(data, 1, paste0, collapse=".")
        groups <- del.var
    }
    unique.del <- unique(data[, groups])
    data[[".groups"]] <- data[, groups]
    if (!is.null(start)) {
      par <- start
    } else {
      par <- list(theta=getME(model, "theta"))
      if (inherits(model, "glmerMod") &&
          getME(model, "devcomp")$dims[["nAGQ"]]>0) {
        par$fixef <- fixef(model)
      }
    }
    fixed <- fixef(model)
    fixed.1 <- matrix(0, length(unique.del), length(fixed))
    rownames(fixed.1) <- unique.del
    colnames(fixed.1) <- names(fixed)
    Vs <- VarCorr(model)
    nms <- names(Vs)
    sep <- ":"
    if (length(nms) == 1) {
        nms <- ""
        sep <- ""
    }
    vc <- getME(model, "sigma")^2
    names(vc) <- "sigma^2"
    for (i in 1:length(Vs)){
        V <- Vs[[i]]
        c.names <- colnames(V)
        e.names <- outer(c.names, c.names, function(a, b) paste0("C[", a, ",", b, "]"))
        diag(e.names) <- paste0("v[", c.names, "]")
        v <- V[lower.tri(V, diag=TRUE)]
        names(v) <- paste0(nms[i], sep, e.names[lower.tri(e.names, diag=TRUE)])
        vc <- c(vc, v)
    }
    vc.1 <- matrix(0, length(unique.del), length(vc))
    rownames(vc.1) <- unique.del
    colnames(vc.1) <- names(vc)
    feval <- numeric(length(unique.del))
    converged <- logical(length(unique.del))
    vcov.1 <- vector(length(unique.del), mode="list")
    names(vcov.1) <- names(feval) <- names(converged) <- unique.del
    # control <- if (one.step){
    #     if (inherits(model, "lmerMod")) lmerControl(optimizer="optimx", optCtrl=list(method="L-BFGS-B", maxit=1))
    #     else if (inherits(model, "glmerMod")) glmerControl(optimizer="optimx", optCtrl=list(method="L-BFGS-B", maxit=1))
    # } else {
    control <- if (inherits(model, "lmerMod")) lmerControl(optCtrl=list(maxfun=maxfun))
        else if (inherits(model, "glmerMod")) glmerControl(optCtrl=list(maxfun=maxfun))
                                        # }
    deleteGroup <- function(del) {
        data$del <- del
        mod.1 <- suppressWarnings(update(model, data=data,
                                         subset=(.groups != del),
                                         start=par,
                                         control=control))

        opt <- mod.1@optinfo
        feval <- opt$feval
        converged <- opt$conv$opt == 0 && length(opt$warnings) == 0
        fixed.1 <- fixef(mod.1)
        Vs.1 <- VarCorr(mod.1)
        vc.0 <- getME(mod.1, "sigma")^2
        for (V in Vs.1){
            vc.0 <- c(vc.0, V[lower.tri(V, diag=TRUE)])
        }
        vc.1 <- vc.0
        vcov.1 <<- .vcov(mod.1)
        namedList(fixed.1, vc.1, vcov.1, converged, feval)
    }
    result <- if (parallel == "multicore") {
        parallel::mclapply(unique.del, deleteGroup, mc.cores = ncpus)
    } else if (parallel == "snow") {
        if (is.null(cl)) {
            cl <- parallel::makeCluster(ncpus)
            on.exit(parallel::stopCluster(cl))
            parallel::clusterEvalQ(cl, require("lme4"))
        }
        parallel::parLapply(cl, unique.del, deleteGroup)
    } else {
        lapply(unique.del, deleteGroup)
    }
    result <- combineLists(result)
    fixed.1 <- result$fixed.1
    rownames(fixed.1) <- unique.del
    colnames(fixed.1) <- names(fixed)
    vc.1 <- result$vc.1
    rownames(vc.1) <- unique.del
    colnames(vc.1) <- names(vc)
    feval <- as.vector(result$feval)
    converged <- as.vector(result$converged)
    vcov.1 <- result$vcov.1
    names(vcov.1) <- names(feval) <- names(converged) <- unique.del
    left <- "[-"
    right <- "]"
    if (groups == ".case") {
        groups <- "case"
    }
    nms <- c("fixed.effects", paste0("fixed.effects", left, groups, right),
             "var.cov.comps", paste0("var.cov.comps", left, groups, right),
             "vcov", paste0("vcov", left, groups, right),
             "groups", "deleted", "converged", "function.evals")
    result <- list(fixed, fixed.1, vc, vc.1,
                   .vcov(model),
                   vcov.1, groups, unique.del, converged, feval)
    names(result) <- nms
    class(result) <- "influence.merMod"
    result
}

## lookup table for influence.merMod elements
ipos <- c("fixed"=1, "fixed.sub"=2,
          "var.cov"=3, "var.cov.sub"=4,
          "vcov"=5, "vcov.sub"=6)

dfbeta.influence.merMod <- function(model, which=c("fixed", "var.cov"), ...){
    which <- match.arg(which)
    b <- model[[ipos[sprintf("%s.sub",which)]]]
    b0 <- model[[ipos[which]]]
    b - matrix(b0, nrow=nrow(b), ncol=ncol(b), byrow=TRUE)
}

dfbetas.influence.merMod <- function(model, ...){
    vList <- model[[ipos["vcov.sub"]]]
    n <- nrow(vList[[1]])
    vmat <- t(vapply(vList, function(x) sqrt(diag(x)),
                     numeric(n)))
    dfbeta(model)/vmat
}

cooks.distance.merMod <- function(model, ...) {
    p <- Matrix::rankMatrix(getME(model,"X"))
    hat <- hatvalues(model)
    dispersion <- sigma(model)^2
    res <- residuals(model,type="pearson")
    res <-  (res/(1 - hat))^2 * hat/(dispersion * p)
    res[is.infinite(res)] <- NaN
    res
}

cooks.distance.influence.merMod <- function(model, ...) {
    db <- dfbeta(model)
    n <- nrow(db)
    p <- ncol(db)
    d <- numeric(n)
    names(d) <- names(model[["vcov[-case]"]])
    vcov.inv <- (n - p)/(n*p)*solve(model$vcov)
    for (i in 1:n) {
        d[i] <- db[i, ] %*% vcov.inv %*% db[i, ]
    }
    d
}

## from ?lm.influence:
##  wt.res: a vector of _weighted_ (or for class 'glm' rather _deviance_)
##          residuals.
##
## residuals.lm gives r*sqrt(object$weights) (if non-NULL weights)
##   for type %in% c("deviance","pearson")
##
## residuals.glm gives  (y - mu) * sqrt(wts)/sqrt(object$family$variance(mu))
##
rstudent.merMod <- function (model, ...) {
    r <- residuals(model, type="deviance")
    hat <- hatvalues(model)
    pr <- residuals(model, type="pearson")
    r <- sign(r) * sqrt(r^2 + (hat * pr^2)/(1 - hat))
    r[is.infinite(r)] <- NaN
    r/sigma(model)
}

rstandard.glmerMod <- function (model,
                              infl = influence(model, do.coef = FALSE),
                              type = c("pearson", "deviance"), ...)
{
    type <- match.arg(type)
    res <- residuals(model, type = type)
    res <- res/(sigma(model) * sqrt(1 - hatvalues(model)))
    res[is.infinite(res)] <- NaN
    res
}

rstudent.glmerMod <- function(model, infl = influence(model, do.coef=FALSE), ...) {
  useSc <- model@devcomp$dims[["useSc"]]
  if (useSc) return(rstandard(model, infl, type="pearson"))
  residuals(model, type = "pearson")/
    (sigma(model)*sqrt(1 - hatvalues(model)))
}


##' @S3method sigma merMod
sigma.merMod <- function(object, ...) {
    dc <- object@devcomp
    dd <- dc$dims
    if(dd[["useSc"]])
        dc$cmp[[if(dd[["REML"]]) "sigmaREML" else "sigmaML"]] else 1.
}

##' @importFrom stats terms
##' @S3method terms merMod
terms.merMod <- function(x, fixed.only=TRUE, random.only=FALSE, ...) {
    if (missing(fixed.only) && random.only) fixed.only <- FALSE
    if (fixed.only && random.only) stop("can't specify 'only fixed' and 'only random' terms")
    tt <- attr(x@frame,"terms")
    if (fixed.only) {
        ## ... may contain 'data' (needed when formula contains .)
        tt <- terms.formula(formula(x,fixed.only=TRUE), ...)
        attr(tt,"predvars") <- attr(terms(x@frame),"predvars.fixed")
    }
    if (random.only) {
        ff <- reformulas::subbars(formula(x, random.only=TRUE))
        ff <- noSpecials(ff, specials = lme4_specials, delete = FALSE)
        tt <- terms.formula(ff)
        attr(tt,"predvars") <- attr(terms(x@frame),"predvars.random")
    }
    tt
}

##' @importFrom stats update
##' @S3method update merMod
update.merMod <- function(object, formula., ..., evaluate = TRUE) {
    if (is.null(call <- getCall(object)))
        stop("object should contain a 'call' component")
    extras <- match.call(expand.dots = FALSE)$...
    if (!missing(formula.))
        call$formula <- update.formula(formula(object), formula.)
    if (length(extras) > 0) {
        existing <- !is.na(match(names(extras), names(call)))
        for (a in names(extras)[existing]) call[[a]] <- extras[[a]]
        if (any(!existing)) {
            call <- c(as.list(call), extras[!existing])
            call <- as.call(call)
        }
    }
    if (!evaluate) return(call)
    ## should be able to find model components somewhere in (1) formula env; (2) calling env;
    ##  (3) parent frame [plus its parent frames]
    ## see discusion at https://stackoverflow.com/questions/64268994/evaluate-call-when-components-may-be-scattered-among-environments
    ## FIXME: suppressWarnings(update(model)) will give
    ## Error in as.list.environment(X[[i]], ...) :
    ## promise already under evaluation: recursive default argument reference or earlier problems?

    ff <- environment(formula(object))
    pf <- parent.frame()
    sf <- sys.frames()[[1]]
    tryCatch(eval(call,  envir = ff),  ## try formula environment
             error = function(e) {
               tryCatch(eval(call, envir = sf),  ## try stack frame
                        error = function(e) {
                          eval(call, envir=pf) ## try parent frame
                        })
             })

    ##
    ## combf <- tryCatch(
    ##     do.call("c", lapply(list(ff, sf), as.list)),
    ##     error=function(e) as.list(ff)
    ## )
    ## eval(call,combf, enclos=pf)
}