2
votes

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.

1
Make the example more reproducible for people who might want to help you: Not all SO users have x or FRP on their computers! Give at least a thinned version of whatever your very first command is reading in..shekeine
Hi Shekeine, the first line was pasted in error The "rasterize" codes work well from spatialpointsdatafram but not for spatialpolygonsdataframes. that's my challenge.Joke O.
You should provide a sample of your data that other SO users can use to recreate your problem. RobertH below has done this but his data does not reproduce your problem: simply because its not the same data as the one you are working with.shekeine

1 Answers

3
votes

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).