[R] x,y,z table to matrix with x as rows and y as columns

Mark Lyman mark.lyman at gmail.com
Tue Jul 24 21:50:23 CEST 2007

> I am sure I am missing something obvious but I cannot find the  
> function I am looking for. I have a data frame with three columns: X,  
> Y and Z, with X and Y being grid coordinates and Z the value  
> associated with these coordinates. I want to transform this data  
> frame in a matrix of Z values, on the grid defined by X and Y (and,  
> as a plus, fill the X.Y combinations which do no exist in the  
> original data frame with NAs in the resulting matrix). I could do  
> this manually but I guess the appropriate function should be  
> somewhere around. I just can't find it.

Immediately after my last post I realized there was a much better solution

> mydat <- expand.grid(x=1:5, y=1:5)
> mydat <- data.frame(mydat, z=rnorm(25))
> mydat$z[sample(1:25,4)] <- NA
> data2mat <- function(x, y, z)
+ {
+ out <- matrix(unlist(split(z, interaction(x,y))), ncol=length(unique(y)))
+ dimnames(out) <- list(unique(x), unique(y))
+ out
+ }
> with(mydat, data2mat(x, y, z))

Mark Lyman

More information about the R-help mailing list