Reputation: 75
I have a problem with my code in R. So, i have a SpatRaster (which im not allowed to provide), that i want to use as a mask. The resolution is 5 Meters, crs is EPSG:32632. Extent is roughly 10km². The Values of the desired shape are all 1 and all other raster values are NA. So i want to create a buffer of 15 Meters around the shape like in the example.
I'm using R 4.3.1 and RStudio, working in a Markdown. Package terra verion 1.7-55
library(terra)
# Load example file
r <- rast(system.file("ex/elev.tif", package="terra"))
r <- project(r, "EPSG:32632")
r <- ifel(r<400, NA, 1)
# Create buffer of 3 Pixels
b <- buffer(r, width = xres(r)*3)
# Show results
par(mfrow = c(1,2))
plot(r)
plot(b)
Plot without buffer and plot with buffer
The result ends up with a raster image where all values in the raster are 1. I tried changing some values, e.g. i changed width to 150, then the buffer works sometimes as desired and i get a 150m buffer (at least fits from visual judgement). But sometimes the 150 buffer also returns an all TRUE Raster image. No other width has yet created a visual appealing result at all. And since this seems to occur random i have no further idea what to do...
Update: While writing this issue, i ran the code (with width 15) again and again stupidly without changing anything, and now i got a fitting result. I safed it for now, but I'm still extremely confused and need my code for further reproduction. So I'm still interested in the error here..
Update 2: Ive added an example, however i cant reproduce the error without the actual dataset. In my case this code mostly produced a shape containing only the value 1, without any NAs or 0. But running the code again and again fixed it eventually.
Update 3: The Bug still occurs with the exact same code. The result i get looks like that, however, the example doesnt generate this bug..
Actual plot without buffer and with buffer
I really dont know whats wrong with it, since the same code works with the examples.
Thanks in regards!
Upvotes: 1
Views: 143
Reputation: 75
It seems like the solution is the available RAM. If i run gc()
right before buffer()
, the result always is the desired result. I have 16GB RAM, im close to 10GB Ram used when buffer()
is used in the script. I don't know the threshold, how much RAM has to be available for buffer()
to work properly, but cleaning up here and there in the script seems to be a good idea.
Thanks for your help!
Upvotes: 1