[R-sig-Geo] Extracting a single grid cell from a SpatialGrid keeping the grid structure

Martin Ivanov tramni at abv.bg
Fri Apr 28 10:09:41 CEST 2017


Hello,
I would like to extract a single grid cell from a SpatialGrid or a SpatialGridDataFrame object without destroying the grid structure, that is, the resulting object must be 
a SpatialGrid or a SpatialGridDataFrame consisting of a single grid cell. Here is a minimum working example:

library(sp);
data(meuse.grid);
coordinates(meuse.grid) = c("x", "y") # promote to SpatialPointsDataFrame
gridded(meuse.grid) <- TRUE # promote to SpatialPixelsDataFrame
x <- as(meuse.grid, "SpatialGridDataFrame") # creates the full grid
fullgrid(meuse.grid) <- TRUE
image(meuse.grid);

# The following works:
latInd <- 20:70; lonInd <- 10:70; # the grid cell indices along latitude and longitude, respectively
a_df <- meuse.grid[latInd, lonInd, "dist"]; # the example SpatialGridDataFrame object
 a_grid <- as(meuse.grid, "SpatialGrid"); # the example SpatialGrid object
image(a_df, add = TRUE, col = bpy.colors());
# the following prints a warning and assumes the grid cellsize of the single-cell dimension is equal to the cellsize of the 
# other dimension, which is not always appropriate:
lonInd <- 50;
a1_df <- meuse.grid[latInd, lonInd, "dist"]; image(a1_df);
# the following returns a SpatialPointsDataFrame object, which is not what is desired:
latInd <- 50;
a11_df <- meuse.grid[latInd, lonInd, "dist"];
# The following simply fails:
a11_grid <- a_grid[latInd, lonInd];

# a way round is to go through a RasterLayer object:
library(raster);
latInd <- a_grid at grid@cells.dim[2] - latInd + 1; a11_grid <- raster(x=a_grid);
# this is for the SpatialGrid case:
a11_grid <- crop(x=a11_grid, y=extent(x=a11_grid, r1=tail(x=latInd, n=1), r2=latInd[1], c1=lonInd[1], c2=tail(x=lonInd, n=1)));
a11_grid <- as(object=a11_grid, Class="SpatialGrid");
# and this is for the SpatialGridDataFrame case:
a11_df <- raster(x=meuse.grid["dist"]);
a11_df <- crop(x=a11_df, y=extent(x=a11_df, r1=tail(x=latInd, n=1), r2=latInd[1], c1=lonInd[1], c2=tail(x=lonInd, n=1)));
a11_df <- as(object=a11_df, Class="SpatialGridDataFrame");
# This approach also works if I only want to extract a single spatial column or a single spatial row and still keep the original grid structure

I would like to ask if there is a simpler and more elegant way to avoid the RasterLayer object? Certainly, this can be achieved directly by hacking the code of the 
"[" operator for the SpatialGrid and the SpatialGridDataFrame classes. However, I do not know how to access that code ... 

Any suggestions will be appreciated.

Thank you very much for your attention and your time.

Best regards,
Martin



More information about the R-sig-Geo mailing list