Skip to content

SpatialGrid from matrix

4 messages · pedro at dpi.inpe.br, Michael Sumner, Edzer Pebesma

#
Hi,

I would like to know how to create a SpatialGrid(DataFrame) using 
directly one matrix as input. I tried to use grid.topology (as shown in 
            the manual), but I got a memory allocation problem (it 
tries to alloc a
vector of size 390Mb using the following script:

require(splancs)
data(bodmin)
x= kernel2d(as.points(bodmin), bodmin$poly, h0=2, nx=100, ny=100)
require(sp)
g=expand.grid(x$x,x$y,x$z)

The last line gives the following error:
Error: cannot allocate vector of size 390625 Kb

Just to show that the data is not so large:
[1] "matrix"
[1] 10000

Is there any other way to create a SpatialGrid without using so much memory?

Thanks,

Pedro Andrade
#
You are expanding your grid for every cell in the matrix, per every grid 
location - which *really is* a lot of memory.  You really want something 
like this:

g <- cbind(expand.grid(x = x$x, y = x$y), as.vector(x$z))
coordinates(g) <- c("x", "y")
gridded(g) <- TRUE
image(g)
contour(x, add = T)  ## just to be sure

I'm pretty sure the ordering is right for this case, but be sure to check.

Cheers, Mike.
#
Michael Sumner wrote:

            
Thanks, Mike, that's an excellent solution.

In this way g is of

 > class(g)
[1] "SpatialPixelsDataFrame"
attr(,"package")
[1] "sp"

meaning that it stores x and y coordinates. To save this
space, you could store it as SpatialGridDataFrame:
 > object.size(g)
[1] 283528
 > fullgrid(g)=T
 > object.size(g)
[1] 83476
 > class(g)
[1] "SpatialGridDataFrame"
attr(,"package")
[1] "sp"

A direct way to create a SpatialGridDataFrame without
using expand.grid() would use GridTopology() and
SpatialGridDataFrame(). You'd have to reorder x$z
for that, too.
--
Edzer
#
Very nice! Also now the size of the Spatial object is almost the same 
of the kernel's result:
[1] 83476
[1] 82224

Thanks!

Pedro Andrade

Quoting "Edzer J. Pebesma" <e.pebesma at geo.uu.nl>: