[R] unexpected behavior of trellis calls inside a user-defined function
Jenny Bryan
jenny at stat.ubc.ca
Thu Mar 22 23:08:09 CET 2007
I am making a battery of levelplots and wireframes for several fitted
models. I wrote a function that takes the fitted model object as the
sole argument and produces these plots. Various strange behavior
ensued, but I have identified one very concrete issue (illustrated
below): when my figure-drawing function includes the addition of
points/lines to trellis plots, some of the information (main title,
placement of additional points) from my i-th function call is leaking
over into the i+1-th call. In the example below, I just get
unexpected results. In my actual application, it breaks the whole
function and one of the error messages I've gotten is:
> figFun(smoothFit1) ## no longer worked, once I got fancy with trellis
Error in depth(path) : no applicable method for "depth"
Smallest example I could construct to illustrate at least one of my
problems:
predVals <-
expand.grid(list(Sepal.Length = seq(from = min(iris$Sepal.Length),
to = max(iris$Sepal.Length), length = 50),
Petal.Length = seq(from = min(iris$Petal.Length),
to = max(iris$Petal.Length), length = 50)))
irisFit <- lm(Sepal.Width ~ Sepal.Length * Petal.Length, data = iris)
predSurf <- data.frame(predVals, Sepal.Width = predict(irisFit,
predVals))
trellis.device("X11",width = 8, height = 8)
levelplot(Sepal.Width ~ Sepal.Length * Petal.Length,
predSurf, main = "Produced at command line, Take 1")
# put levelplot call inside a function
myFunction <- function(surf) {
levelplot(Sepal.Width ~ Sepal.Length * Petal.Length,surf,
main = "Produced by function, Take 1")
}
myFunction(predSurf)
# OK, get the expected figure result
## now .. what if we add points to the plot?
levelplot(Sepal.Width ~ Sepal.Length * Petal.Length,
predSurf, main = "Produced at command line, Take 2")
trellis.focus("panel", 1, 1) # address the correct part of the
figure
lpoints(6,4,pch = 19, cex = 2) # a point appears in correct location
# I get what I expect
## any crosstalk from adjacent command line invocations? no
levelplot(Sepal.Width ~ Sepal.Length * Petal.Length,
predSurf, main = "Produced at command line, Take 3")
trellis.focus("panel", 1, 1) # address the correct part of the
figure
lpoints(5,2,pch = 19, cex = 2) # a point appears in correct location
# I get what I expect
# put all this inside a function
myFunction <- function(surf) {
levelplot(Sepal.Width ~ Sepal.Length * Petal.Length,surf,
main = "Produced by function, Take 2")
trellis.focus("panel", 1, 1) # address the correct part of the
lpoints(7,5,pch = 19, cex = 2) # a point appears in correct location
}
myFunction(predSurf)
# the title still says "Produced at command line, Take 3"
# and points appear at (5,2) AND (7,5) ... why?
More information about the R-help
mailing list