CARLOS_BEDSON
CARLOS_BEDSON

Reputation: 53

Error on terra:rasterize -not taking all point values

I am trying to generate random points on a polygon with each having a separate ID number and then converting to a raster for subsequent use in Circuitscape. For some reason "Rasterize" function seems to change its treatment of the point values each time and some get repeated and some are lost. Please any advice. Thank you. Carlos

library(terra)
library(sf)
RASTER <- rast(nrow=10, ncol=10, ext=c(0, 100, 0,100), crs= "EPSG:27700", vals=1) 
VECT <- vect(ext(0, 100, 0,100), crs="epsg:27700")
#plot(RASTER); lines(VECT)
POLYGON <- st_as_sf(VECT) # CONVERT TO SF
POLYGON <- st_cast(POLYGON, "MULTILINESTRING") # TO MULTIINE STRING 
POLYGON.NODES <- st_sample(POLYGON, 10, type="regular") # SAMPLE 
NODES.NUMBERS <- as.numeric(seq(from = 1, to = 10, by = 1)) # AS VECTOR 
NODES.NUMBERS
# [1]  1  2  3  4  5  6  7  8  9 10
POLYGON.NODES <- merge(POLYGON.NODES, NODES.NUMBERS) # BECOMES DATAFRAME
POLYGON.NODES
#                         geometry  y
#1  MULTIPOINT ((0 32.60739), (...  1
#2  MULTIPOINT ((0 32.60739), (...  2
#3  MULTIPOINT ((0 32.60739), (...  3
#4  MULTIPOINT ((0 32.60739), (...  4
#5  MULTIPOINT ((0 32.60739), (...  5
#6  MULTIPOINT ((0 32.60739), (...  6
#7  MULTIPOINT ((0 32.60739), (...  7
#8  MULTIPOINT ((0 32.60739), (...  8
#9  MULTIPOINT ((0 32.60739), (...  9
#10 MULTIPOINT ((0 32.60739), (... 10
POLYGON.NODES <- st_sf(POLYGON.NODES)# WORKS BECOMES SF MULTIPOINT OBJECT AND DF 
POLYGON.NODES <- vect(POLYGON.NODES) # BECOMES SPATVEC

And now

POLYGON.NODES.RASTER <- rasterize(POLYGON.NODES, RASTER, "y")
POLYGON.NODES.RASTER
#class       : SpatRaster 
#dimensions  : 10, 10, 1  (nrow, ncol, nlyr)
#resolution  : 10, 10  (x, y)
#extent      : 0, 100, 0, 100  (xmin, xmax, ymin, ymax)
#coord. ref. : OSGB36 / British National Grid (EPSG:27700) 
#source(s)   : memory
#name        : last 
#min value   :    1 
#max value   :   10 
freq(POLYGON.NODES.RASTER) # RESULTS HAVE LOST THE SEQUENCE FROM 1 TO 10 
#  layer value count
#1     1     1     1
#2     1     3     1
#3     1     5     2
#4     1     6     1
#5     1     7     2
#6     1     8     2
#7     1    10     1
plot(POLYGON.NODES.RASTER) # SHOWS SOME WITH SAME ID

enter image description here

Upvotes: 0

Views: 89

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47546

You can do

library(terra)
library(sf)
r <- rast(nrow=10, ncol=10, ext=c(0, 100, 0,100), crs= "EPSG:27700", vals=1) 
v <- vect(ext(0, 100, 0,100), crs="epsg:27700") |> as.lines()
nodes <- st_sample(st_as_sf(v), 10, type="regular") 
# disaggregate to go from multipoint to point
v <- disagg(vect(nodes))  
v$ID <- 1:10

pr <- rasterize(v, r, "ID")
plot(pr, type="classes"); text(pr, halo=T)

The object you create for rasterizing is SpatVector of 10 multipoint geometries of 10 points each.

Upvotes: 1

Related Questions