File: lmrobPredict.R

package info (click to toggle)
robustbase 0.8-1-1-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 3,156 kB
  • sloc: fortran: 2,553; ansic: 2,419; makefile: 1
file content (192 lines) | stat: -rw-r--r-- 7,614 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
#  File .../lmrobPredict.R
#  Part of the R package 'robustbase', http://www.R-project.org
#  Based on predict.lm (cf. src/library/stats/R/lm.R)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  A copy of the GNU General Public License is available at
#  http://www.r-project.org/Licenses/

# Note that '# *rob' indicate adjustment for the robust case

predict.lmrob <-
    function(object, newdata, se.fit = FALSE, scale = NULL, df = NULL,  # *rob
	     interval = c("none", "confidence", "prediction"),
	     level = .95,  type = c("response", "terms"),
	     terms = NULL, na.action = na.pass, pred.var = res.var/weights,
             weights = 1, ...)
{
    tt <- terms(object)
    if(!inherits(object, "lmrob") && !inherits(object, "glmrob")) # *rob
	warning("calling predict.lm(<fake-lmrob-object>) ...") # *rob
    if(missing(newdata) || is.null(newdata)) {
	mm <- X <- model.matrix.lm(object)
	mmDone <- TRUE
	offset <- object$offset
    }
    else {
        Terms <- delete.response(tt)
        m <- model.frame(Terms, newdata, na.action = na.action,
                         xlev = object$xlevels)
        if(!is.null(cl <- attr(Terms, "dataClasses"))) .checkMFClasses(cl, m)
        X <- model.matrix(Terms, m, contrasts.arg = object$contrasts)
        offset <- rep.int(0, nrow(X))
        if (!is.null(off.num <- attr(tt, "offset")))
            for(i in off.num)
                offset <- offset + eval(attr(tt, "variables")[[i+1]], newdata)
	if (!is.null(object$call$offset))
	    offset <- offset + eval(object$call$offset, newdata)
	mmDone <- FALSE
    }
    n <- length(object$residuals) # NROW(qr(object)$qr)
    p <- object$rank
    ## *rob: FIXME? predict.lm() here does pivoting and rank/ column selection
    if(is.null(p)) df <- Inf   # *rob
    if(any(is.na(beta <- object$coefficients)))   # *rob
        stop("there are NAs in the coefficients") # *rob
    predictor <- drop(X %*% beta)                 # *rob
    if (!is.null(offset))
	predictor <- predictor + offset

    interval <- match.arg(interval)
    if (interval == "prediction") {
        if (missing(newdata)) { # *rob: this and next if statement are combined
            warning("Predictions on current data refer to _future_ responses\n")
            if (missing(weights)) {
                w <- stats:::weights.default(object) # *rob
                if (!is.null(w)) {
                    weights <- w
                    warning("Assuming prediction variance inversely proportional to weights used for fitting\n")
                }
            }
        }
        if (!missing(newdata) && missing(weights) && !is.null(object$weights) && missing(pred.var))
            warning("Assuming constant prediction variance even though model fit is weighted\n")
        if (inherits(weights, "formula")){
            if (length(weights) != 2L)
                stop("'weights' as formula should be one-sided")
            d <- if(missing(newdata) || is.null(newdata))
                model.frame(object)
            else
                newdata
            weights <- eval(weights[[2L]], d, environment(weights))
        }
    }## "prediction" interval

    type <- match.arg(type)
    if(se.fit || interval != "none") {# *rob: whole 'then' statement is different
        df <- object$df.residual
	res.var <- if (is.null(scale)) object$s^2  else scale^2
	if(type != "terms"){
             ip <- diag(X %*% object$cov %*% t(X))
        } else ip <- rep.int(0, n)
    }

    if (type == "terms") { ## type == "terms" ------------

	if(!mmDone){
            mm <- model.matrix.lm(object) # *rob: call of model.matrix.lm
                                        # instead of model.matrix
            mmDone <- TRUE
        }
        aa <- attr(mm, "assign")
	ll <- attr(tt, "term.labels")
	hasintercept <- attr(tt, "intercept") > 0L
	if (hasintercept) ll <- c("(Intercept)", ll)
	aaa <- factor(aa, labels = ll)
	asgn <- split(order(aa), aaa)
	if (hasintercept) {
	    asgn$"(Intercept)" <- NULL
	    if(!mmDone){
                mm <- model.matrix.lm(object) # *rob: call of model.matrix.lm
                                        # instead of model.matrix
                mmDone <- TRUE
            }
	    avx <- colMeans(mm)
	    termsconst <- sum(avx * beta) # *rob: no column selection
	}
	nterms <- length(asgn)
        if(nterms > 0) {
            predictor <- matrix(ncol = nterms, nrow = NROW(X))
            dimnames(predictor) <- list(rownames(X), names(asgn))

            if (se.fit || interval != "none") {
                ip <- predictor # *rob: just this assignment is needed
            }
             if(hasintercept)
                X <- sweep(X, 2L, avx, check.margin=FALSE)
            unpiv <- seq_len(NCOL(X))
            ## *rob: Assuming there are no columns which are
            ##      completely aliased with earlier columns.
            for (i in seq.int(1L, nterms, length.out = nterms)) {
                iipiv <- asgn[[i]]      # Columns of X, ith term
                ii <- unpiv[iipiv]      # Corresponding rows of Rinv
                iipiv[ii == 0L] <- 0L
                predictor[, i] <-
                    if(any(iipiv > 0L)) X[, iipiv, drop = FALSE] %*% beta[iipiv]
                    else 0
                if (se.fit || interval != "none"){
                    ip[, i] <- if(any(iipiv > 0L)){# *rob: next steps modified
                        h.X <- X[, iipiv, drop = FALSE]
                        diag(h.X %*%object$cov[iipiv, iipiv] %*% t(h.X))
                    } else 0
                }
                }
            if (!is.null(terms)) {
                predictor <- predictor[, terms, drop = FALSE]
                if (se.fit)
                    ip <- ip[, terms, drop = FALSE]
            }
        } else {                        # no terms
            predictor <- ip <- matrix(0, n, 0L)
        }
	attr(predictor, 'constant') <- if (hasintercept) termsconst else 0
    }

### Now construct elements of the list that will be returned

    if(interval != "none") {
	tfrac <- qt((1 - level)/2, df)
	hwid <- tfrac * switch(interval,
			       confidence = sqrt(ip),
			       prediction = sqrt(ip+pred.var)
			       )
	if(type != "terms") {
	    predictor <- cbind(predictor, predictor + hwid %o% c(1, -1))
	    colnames(predictor) <- c("fit", "lwr", "upr")
	} else {
            if (!is.null(terms)) hwid <- hwid[, terms, drop = FALSE]
	    lwr <- predictor + hwid
	    upr <- predictor - hwid
	}
    }
    if(se.fit || interval != "none") {
        se <- sqrt(ip)
        if (type == "terms" && !is.null(terms)) se <- se[, terms, drop = FALSE]
    }
    if(missing(newdata) && !is.null(na.act <- object$na.action)) {
	predictor <- napredict(na.act, predictor)
	if(se.fit) se <- napredict(na.act, se)
    }
    if(type == "terms" && interval != "none") {
	if(missing(newdata) && !is.null(na.act)) {
	    lwr <- napredict(na.act, lwr)
	    upr <- napredict(na.act, upr)
	}
	list(fit = predictor, se.fit = se, lwr = lwr, upr = upr,
	     df = df, residual.scale = sqrt(res.var))
    } else if (se.fit)
        list(fit = predictor, se.fit = se,
             df = df, residual.scale = sqrt(res.var))
    else predictor
}