From k.hansen at biostat.ku.dk  Thu Mar 18 13:36:01 2004
From: k.hansen at biostat.ku.dk (k.hansen@biostat.ku.dk)
Date: Thu Mar 18 13:35:55 2004
Subject: [Rd] termplot has problems with a single term (fix included)
	(PR#6675)
Message-ID: <20040318123601.081D210429@slim.kubism.ku.dk>

The bug exists on R-1.9.0-alpha compiled the 10/3.

Termplot has a problem if either the model only contains a single term
or if asked to plot a single term. In addition there are problems with
the option se = TRUE.

Analysis: termplot starts with 

  terms <- if (is.null(terms)) 
    predict(model, type = "terms", se = se)
  else predict(model, type = "terms", se = se, terms = terms)
  n.tms <- ncol(tms <- as.matrix(if (se) 
                                 terms$fit
  else terms))

In this case terms is now a matrix of fitted values, with a single
column for each term in the model or in the terms argument. Because
the predict function returns a vector if called with a single term,
the matrix tms has no column names. This maskes the lines
  nmt <- colnames(tms)
  cn <- parse(text = nmt)
fail.

Solution: manually add the column names in case the number of columns
of tms == 1. Beware that the terms argument is overwritten in the
first line of the function (Is that a good style? Perhaps the body of
the function needs another name for the terms object defined in the
very first line). This means we manually need to save the terms name
first (code below)

Fixing this bug uncovers another one: in case of a single term in the
model formula, and with the option se = TRUE, the terms objects
consists of a list with elements fit and se.fit. In the code above
explicit care is taken to ensure that the fit element is a matrix by
using 
  tms <- as.matrix(if (se) terms$fit
                   else terms)
The element se.fit needs to be a matrix as well. I suggest a final fix
to be

{
*  terms.names <- terms
   terms <- if (is.null(terms)) 
     predict(model, type = "terms", se = se)
   else predict(model, type = "terms", se = se, terms = terms)
   n.tms <- ncol(tms <- as.matrix(if (se) 
                                  terms$fit
   else terms))
*  if(n.tms==1)
*    colnames(tms) <- if(is.null(terms)) attr(model$terms, "term.labels")
*                        else terms.names
*  if(se)
*    terms$se.fit <- as.matrix(terms$se.fit)

* = added line.


The fix above is somewhat ugly. Perhaps (as mentioned above) the
object terms needs renaming (terms.something?), in which case the
first line is redundant.
-- 
Kasper Daniel Hansen, Research Assistent
Department of Biostatistics, University of Copenhagen


[Rd] termplot has problems with a single term (fix included) (PR#6675)
k.hansen@biostat.ku.dk