Re: [S] Re: bug in predict()

Prof Brian D Ripley (ripley@stats.ox.ac.uk)
Mon, 18 May 1998 17:37:47 +0100 (BST)


On Sun, 17 May 1998, Frank E Harrell Jr wrote:

> >This is the price to pay to work in an OOP environment.
>
> Not necessarily. In me Design library I go to great pains so that the
> user doesn't need to worry about this problem at all. predict.Design
> re-maps factor levels back to the way they were in the original fit.
>

Well, as predict.Design is not a generic function, it is not really in the
OOP environment. Just to show that it can be do there, here is

predict <- function(object, newdata, ...)
{
changed <- F
if(!missing(newdata) &&
length(data <- eval(substitute(object$call$data))))
{
olddata <- eval(parse(text=deparse(data)), sys.parent())
if(is.data.frame(olddata) &&
any(facs <- sapply(olddata, is.factor))) {
olev <- lapply(olddata, levels)
nlev <- lapply(newdata, levels)
pos <- match(names(newdata), names(olddata), 0)
for(i in seq(along=facs)[facs])
if((j <- pos[i]) > 0 &&
(length(nlev[[i]]) != length(olev[[j]]) ||
any(nlev[[i]] != olev[[j]]))) {
newdata[[i]] <- factor(as.character(newdata[[i]]),
levels=olev[[j]])
changed <- T
}
}
}
if(changed) {
call <- match.call()
call[[1]] <- predict
call$newdata <- newdata
eval(call, sys.parent())
} else UseMethod("predict")
}

This tries to fix up any factors in newdata that are also in the data
argument of the original call, presuming that is unchanged. Although
it will work as predict, I do suggest that you rename it to, say,
spredict, to avoid confusion later.

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

----------------------------------------------------------------------- This message was distributed by s-news@wubios.wustl.edu. To unsubscribe send e-mail to s-news-request@wubios.wustl.edu with the BODY of the message: unsubscribe s-news