Saturday, 16 May 2015

raster - How to rasterize a vector dataset in R?


I would like to compare vector vs raster data. So i try to fix a problem using both ways.


I made it in vector first :


coastline<-readShapeSpatial("shp")
wets<-readShapeSpatial("shp")
wetb<-gBuffer(wets,width=500,byid=T) #doing a buffer of 500m of the wetlands
wetb2<-gBuffer(wets,width=1000,byid=T) #doing abuffer of 1000
wetb1$vat=0 # assigning a new column of 0 in the buffer i created

wetb2$vat=5 # assigning a new column of 5 in the second buffer
coastline$vat=10 #assigning a new column of 10 in the rest of the land

Now how would i write the same thing in raster?


My thoughts are that i should turn the coastline and the wetlands into raster first off.How would i do that and what after that?



Answer



Here's a suggestion:


# Use rgdal, better library
library(rgdal)
coastline <- readOGR(dsn=".", layer="coastline")

wets <- readOGR(dsn=".", layer="wets")

Rasterize 'em:


require(raster)
# Create a generic raster, set the extent to the same as wetlands
r.raster <- raster()

Use extent (from raster package) to read bounds of vector and assign to the raster:


extent(r.raster) <- extent(wets)
res(r.raster) <- 2500 # set cell size to 2500 metres


# Make a raster of the wetlands:
coastline.r <- rasterize(wets, r.raster)

# Do the same buffering operation but in raster:
wetb <- buffer(wets, width=500)

If you want to do it by individual features, you could loop through them and create a raster stack layer for each feature.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...