Joke O.
Joke O.

Reputation: 599

Rasterize spatialpolygons in R giving raster with NA values

I am having issues converting this spatialpolygondataframe to a raster. When I do ther conversion, the raster has NA as its values. As shown below:

 DL3
[1]
class       : SpatialPolygonsDataFrame 
features    : 126 
extent      : -15.04001, 46.1036, 3.759985, 31.71804  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +towgs84=0,0,0 +ellps=WGS84 
variables   : 1
names       :  LFRP 
min values  :    14 
max values  : 335.2 

This is how I rasterize it:

##TO CONVERT TO RASTER
FunR<-function(r){
ext<-raster(extent(r))
crs(ext)<-crs(r)
D<-rasterize(r,ext,field=1,update=T)
D}

DL4<-lapply(DL3,FunR)
DL4
[1]
class       : RasterLayer 
dimensions  : 45, 40, 1800  (nrow, ncol, ncell)
resolution  : 1.52859, 0.6212901  (x, y)
extent      : -15.04001, 46.1036, 3.759985, 31.71804  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +towgs84=0,0,0 +ellps=WGS84 
data source : in memory
names       : layer 
values      : NA, NA  (min, max)

What can I be doing wrongly? I need help with a method to ensure the values in the dataframe reflect in the raster, please.

Upvotes: 2

Views: 2371

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47051

The principle works, as illustrated below.

library(raster)
SPP <- shapefile(system.file("external/lux.shp", package="raster"))
r <- raster(SPP, ncol=40, nrow=45)    
SPP2 <- rasterize(SPP, r, "ID_1")

As this does not work for you, I assume that your polygons are very small relative to the raster cell size such that none of the cells is covered. Can you try with much smaller grid cells? If indeed the polygons are that small, it might make more sense to use their centroids (coordinates(SPP)) and rasterize these (as points).

Upvotes: 3

Related Questions