Skip to content
Prev 15660 / 29559 Next

melt spatialPixelDataFrame

The culprit in raster_2.0-08 is in R/as.data.frame.R

setMethod('as.data.frame', signature(x='SpatialPoints'),

and the relevant usage is in (raster's) ?as.data.frame "Get a
data.frame with raster cell values, or coerce a SpatialPolygons,
Lines, or Points file to a data.frame"

 ## S4 method for signature 'SpatialPoints'
     as.data.frame(x, row.names=NULL, optional=FALSE, xy=FALSE, ...)


So, you can get similar to the sp behaviour if you use xy = TRUE, but
note that this is a completely different pathway and logic to the way
the sp:::as.data.frame.SpatialPixelsDataFrame works (it passes the job
to sp:::as.data.frame.SpatialPointsDataFrame).

library(sp)
data(meuse.grid)
m = SpatialPixelsDataFrame(points = meuse.grid[c("x", "y")], data = meuse.grid)
head(as.data.frame(m))

library(raster)
as.data.frame(m, xy = TRUE)
  object      x      y    x.1    y.1 part.a part.b      dist soil ffreq
1      1 181180 333740 181180 333740      1      0 0.0000000    1     1
2      2 181140 333700 181140 333700      1      0 0.0000000    1     1
...

I haven't followed the trail to where the "object" column is removed
again when using as.data.frame(m) with raster loaded.

raster introduces as.data.frame as a generic, with methods for
SpatialPoints, SpatialLines and SpatialPolygons, and the
SpatialPixelsDataFrame must get captured by the "SpatialPoints" one,
which has checks for the @data slot, which seems like a catch-all that
breaks the sp model. Summary is, if you use raster you accept a
completely different paradigm that you might be used to with sp.

Cheers, Mike.
On Thu, Jul 19, 2012 at 12:59 AM, Michael Sumner <mdsumner at gmail.com> wrote: