# [R] Why does this work?

Paul Murrell p.murrell at auckland.ac.nz
Wed May 29 00:25:15 CEST 2002

```Hi

> I waxs just checking examples in lattice levelplot and I ran into this
> strange (?) behavior I do not understand.
>
> Here is the example:
>
>      x <- seq(pi/4, 5*pi, length = 100)
>      y <- seq(pi/4, 5*pi, length = 100)
>      r <- sqrt(outer(x^2, y^2, "+"))
>      grid <- expand.grid(x=x, y=y)
>
> At this point grid is a 10000*2 data frame and r is a 100*100 matrix.  Now
> comes a surprising part.
>
>      grid\$z <- cos(r^2) * exp(-r/(pi^3))
>
> This does not generate any error.  But typing
>
>      grid
>
> produces
>
>       Error in data.frame(x = c(" 0.7853982", " 0.9361311", " 1.0868641", "
> 1.2375971",  :
>              arguments imply differing number of rows: 10000, 100
>
> Moreover
>
>      dim(grid)
>       10000     3
>
> but
>
>      grid[1:5, ]
>
> produces an output with 102 columns named x, y, z.1, ..., z.100
>
> and
>
>      grid[101, ]
>
> produces "subscript out of bound" error.
>
> Finally
>
>      levelplot(z~x*y, grid, cuts = 50, xlab="", ylab="", main="Weird
> Function", colorkey = FALSE)
>
> generates a proper contour plot.  Could somebody explain to me why this
> actually works?  Thanks in advance,

I think the problem is that grid\$z has a "dim" attribute which means
that it is being treated as a matrix in some of the cases above.
Compare ...

attributes(grid\$x)
attributes(grid\$y)
attributes(grid\$z)

... You can also see this if you just do ...

grid\$x
grid\$y
grid\$z

... grid\$x and grid\$y are just vectors of 10000 values, but grid\$z is a
100x100 matrix of values.  Now, if you define grid\$z as ...

grid\$z <- as.numeric(cos(r^2) * exp(-r/(pi^3)))

... ALL of your examples work (grid\$z no longer has a "dim" attribute).
The examples that worked before were presumably doing an explicit
as.numeric() conversion already (or were just not checking for the "dim"
attribute).

Hope that helps.

Paul
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```