Tyler
Tyler

Reputation: 10032

R: Plotting matrix columns using formulas

Having just spent an hour chasing a 'matrix vs data.frame' bug in my code, I would very much like to understand the following:

tmp <-
  structure(c(4L, 7L, 5L, 12L, 6L, 11L, 9L, 3L, 1L, 2L, 10L, 8L),
            .Dim = c(6L, 2L), .Dimnames = list(NULL, c("col1", "col2")))

## 1. This works:
plot(col2 ~ col1, data = tmp)

## 2. This doesn't work:
plot(col2 ~ col1, data = tmp, main = "hello")
## -> Error in FUN(X[[1L]], ...) : numeric 'envir' arg not of length one

## 3. This works:
plot(col2 ~ col1, data = as.data.frame(tmp), main = "hello")

It seems to me that either 1 and 2 should both work, or both fail. The fact that 1 worked while 2 failed lead me very far astray in trying to get my code working.

My question is: why can you sometimes use a formula to plot matrix columns, instead of always or never? What happens when I add a title to my plot to cause it to fail?

Edit: I suspected I must have broken something myself, so I have already tried this exact code in multiple fresh R instances. My sessionInfo is:

> sessionInfo()
R version 2.12.1 (2010-12-16)
Platform: i686-pc-linux-gnu (32-bit)

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_CA.UTF-8   
 [7] LC_PAPER=en_CA.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     
> 

Edit:

Here's the traceback() following the failed plot command:

> > traceback()
4: FUN(X[[1L]], ...)
3: lapply(dots, eval, data, parent.frame())
2: plot.formula(col2 ~ col1, data = tmp, main = "hello")
1: plot(col2 ~ col1, data = tmp, main = "hello")
> 

Edit:

Upgrading to 2.14 has resolved the issue.

Upvotes: 3

Views: 577

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162391

Based on the comments thread following the question, it's clear that this was a problem in R-2.12.1, and isn't for R-2.14.0.

The R-2.13.0 section of the NEWS file is presumably referring to this bug fix when it mentions that

* plot(<formula>, data=<matrix>,..) now works in more cases;
  similarly for points(), lines() and text().

(NOTE: this answer is based on the digging of Tyler and numerous posters above. I'm elevating the conclusions of that thread to answer status, as a possibly useful reminder of the kind of bug-fixes that are included in each version of R.)

Upvotes: 6

Related Questions