[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:33:38 CEST 2007
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
More information about the R-help
mailing list