Spectron
Spectron

Reputation: 23

Creating raster from shapefile in R

I have a shapefile of my study area, and I wanted to create a raster where every cell that belongs to that shapefile has value=1 and the other cells are value=NA.

I wanted to create this new raster with the same origin and cell size as the environmental rasters I will be using in my analysis.

This is the code I'm using, but I always get this error: "Error in rep(value, length.out = 2) : attempt to replicate an object of type 'S4'"

#Create raster from shapefile

library(raster)
library(rgdal)

x <- readOGR(dsn="D:/Mestrado/Tese/AreaEstudo/final", layer="areaestudofinaluniforme")
pad <- raster("D:/Mestrado/Tese/Dados modelação/Mais recente/Variáveis maxent/bio_11.asc")

ext <- extent(pad)
reso <- res(pad)
ori <- origin(pad)

newraster <- raster(x, ext, reso, ori)

(I still haven't figured out how to assign the values to the raster)

Does anyone have any suggestions on why I get this error? And about how I could assign the values I want?

Upvotes: 0

Views: 809

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

You can do

r <- rasterize(x, r, field=1)

To create a new raster, which is not needed here, you can do

y <- raster(x)

Upvotes: 1

Related Questions