2

I'm having trouble rasterizing a shapefile using the raster package in R.

shp<-shapefile(ZoneShape);
lcRas<-raster(lcRaster);

r<-raster(ncol=ncol(lcRas), nrow=nrow(lcRas), crs=CRS);
res(r)<-res(lcRas);
extent(r)<-extent(lcRas);

>r

class       : RasterLayer 
dimensions  : 22610, 27959, 632152990  (nrow, ncol, ncell)
resolution  : 1, 1  (x, y)
extent      : 554739, 582698, 3837197, 3859807  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs +towgs84=0,0,0

shp$GID<-1:nrow(shp);

> shp

class       : SpatialPolygonsDataFrame 
nfeatures   : 1 
extent      : 554838, 582597.6, 3837297, 3859707  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=15 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0 
nvariables  : 14
names       : SP_ID,              NAME, Shape_Leng, Shape_Area, GID

>zoneRas<-rasterize(shp, r, "GID")

The following error is returned:

trying to get slot "coords" from an object of a basic class ("NULL") with no slots.

Can anyone see what I'm missing up here?

  • Guess it'd be much easier for us if you provided some sample data. I just reprogrammed it with some data I found on the web and it worked fine... what are your results for coordinates(r) and coordinates(shp)? – fdetsch Jun 25 '13 at 15:23
  • @flowa. Good suggestion because this script ran for a different dataset. But, still have no idea why this doesn't work. coordinates(r) returns a long vector of coordinates and coordinates(shp) returns a one by two matrix with only two coordinates. Guessing, rasterize is looking for four coordinates. Viewing the shapefile in ArcGIS, it looks good spatially and in the attribute table. I'm not sure how I would share this dataset. At any rate, your suggestion helped me see the issue is in the data, not the code. – RichT Jun 25 '13 at 16:35
  • What do the coordinates of your original raster lcRaster look like? – fdetsch Jun 26 '13 at 7:32
1

This is a bug that happens when the SpatialPolygonsDataFrame object only has a single geometry. Here is a work-around:

zoneRas <- rasterize(shp, r, shp$GID)
1

Ran into the same problem today. Turns out the field I was trying to rasterize was of type "character". I converted it to "numeric", an then the function worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.