2

I am posting my issue in this community as I did not get satisfying answers in stackoverflow, hoping to get a solution here.

I am working on a spatial simulation and I created spatial points, but when I plot them with raster R package I can see that some points are outside the grid in the plot (example 1). Even when I try to define raster base on min and max values of XY coordinates(example 2).

I would like to know how I could be sure that all my points are inside the grid as I need to use polygon ID as localisation for the next steps of my simulations.

This is my code for reproducibility:

Example 1:

library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")
r1 <- raster(tmp, resolution = 10)
r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}

Example 2:

library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")

r1 <- raster(xmn = min(tmp2$x), xmx = max(tmp2$x), 
          ymn = min(tmp2$y), ymx = max(tmp2$y), 
          resolution = 10)

r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}

1 Answer 1

5

Since you set a custom resolution (10), the output raster doesn't have the same boundary box as the points layer, because the raster approximates to the closest value for defining the number of rows/columns:

(max(tmp2$y)-min(tmp2$y))/10
# 6.161062
# and your raster has 6 rows

You can add some extra space if you want to preserve the resolution or define a custom number of rows/columns, but this will create rectangular cells instead of squares.

Adding some extra space:

library(raster)
set.seed(100)
tmp = tmp2 = data.frame("x" = rnorm(1000, 10, 10),"y" = rnorm(1000, 10, 10))
coordinates(tmp) <- c("x", "y")
r1 <- raster(xmn = min(tmp2$x)-2.5, xmx = max(tmp2$x)+2.5, 
             ymn = min(tmp2$y)-2.5, ymx = max(tmp2$y)+2.5, 
             resolution = 10)

r1<-rasterToPolygons(r1)
plot(r1)
for (a in 1:nrow(tmp2)) {
  d = tmp2[a,]
  pts<- d
  coordinates(pts)<-~x+y
  plot(pts,add=T,col=a)
}

enter image description here

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.