Hello all, 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. Thank you in advance for your help. JiHO --- http://jo.irisson.free.fr/
Mark Lyman
2007-Jul-24 19:33 UTC
[R] x,y,z table to matrix with x as rows and y as columns
jiho <jo.irisson <at> gmail.com> writes:> > Hello all, > > 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.I have used xtabs in the past, but xtabs returns 0 instead of NA, which makes great for cross-tabulation, the "offending" line is x[is.na(x)] <- 0. So you would need to either modify the xtabs function or trust that z is never 0 and replace all 0's with NA.> mydat <- expand.grid(x=1:5, y=1:5) > mydat <- data.frame(mydat, z=rnorm(25)) > mydat$z[sample(1:25,4)] <- NA > mytab <- xtabs(z~x+y, mydat)Mark Lyman
Mark Lyman
2007-Jul-24 19:50 UTC
[R] x,y,z table to matrix with x as rows and y as columns
> 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