[R] transforming data frame for use with persp

Roger Bivand Roger.Bivand at nhh.no
Tue Feb 14 09:24:06 CET 2006


On Mon, 13 Feb 2006, Denis Chabot wrote:

> Hi,
> 
> This is probably documented, but I cannot find the right words or  
> expression for a search. My attempts failed.
> 
> I have a data frame of 3 vectors (x, y and z) and would like to  
> transform this so that I could use persp. Presently I have y-level  
> copies of each x level, and a z value for each x-y pair. I need 2  
> columns giving the possible levels of x and y, and then a  
> transformation of z from a long vector into a matrix of x-level rows  
> and y-level columns. How do I accomplish this?

Well, image() and friends have a rather strange representation, so it 
isn't obvious (see the help page:

     "Notice that 'image' interprets the 'z' matrix as a table of
     'f(x[i], y[j])' values, so that the x axis corresponds to row
     number and the y axis to column number, with column 1 at the
     bottom, i.e. a 90 degree counter-clockwise rotation of the
     conventional printed layout of a matrix.").

So:

Depth <- seq(40,220, 20)
Temp <- seq(-1, 6, 0.5)
My.data <- expand.grid(Depth=Depth, Temp=Temp)
predgam <- -0.5*My.data$Depth + 12.5*My.data$Temp + 8*rnorm(nrow(My.data))
pred.data <- data.frame(My.data, predgam)
library(lattice)
levelplot(predgam ~ Depth + Temp, pred.data) # for sanity check
z <- t(matrix(predgam, nrow=length(Temp), byrow=TRUE)) # see "Notice" 
image(Depth, Temp, z)
persp(Depth, Temp, z)

should do it, since the data are already in a regular grid.

> 
> In this example, I made a set of x and y values to get predictions  
> from a GAM, then combined them with the predictions into a data  
> frame. This is the one I'd like to transform as described above:
> 
> My.data <- expand.grid(Depth=seq(40,220, 20), Temp=seq(-1, 6, 0.5))
> predgam <- predict.gam(dxt.gam, My.data, type="response")
> pred.data <- data.frame(My.data, predgam)
> 
> pred.data has 150 lines and 3 columns.
> 
> Thanks for your help,
> 
> Denis Chabot
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> 

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no




More information about the R-help mailing list