I have several cropped rasters with different geometry/outlines. Specifically spatial yield maps from several years of the same field, but the extent varies - the measurements were not always overall the whole field, but in some years only part of it. I want to calculate a mean value of those maps and combine them into one mean-value-raster. That does mean however, that not for every pixel in let's say 5 layers/rasters there is a value. I could accept these missing values to be NA, so the final mean value would only be calculated by let's say 3 rasters for parts of the field, where the maps are not overlapping.
I thought of extending the raster with 'extend{raster}', filling the non-overlapping parts with NA values:
y <- extend(y, shape, value=NA)
#Shape is a rectangular shape that enframes all yield map rasters
That works fine, for all rasters. But they still don't have the same extent. Even if I adjust the extent by setExtent()
or extent() <- extent()
to the extent of the rectangular shapefile or even to one of the other extended rasters, I still get:
Error in compareRaster(x) : different number or columns
..when I want to stack them and use calc(y, fun=mean,...)
. The original raster extents are too different to resample. But they do have the same resolution and CRS.
Has anyone an idea how to solve this?
I had the same problem to satack some rasters, these contain bioclim data. It come up that I did crop correctly, but download them in different resolutions. Have a look on the amount of columns each raster has. It can be done by just typing in R the name of the raster (file). They may be the same size. I hope that I could help somehow.
If you want to achieve an operation such as
calc(y, fun=mean,...)
, you could get the minimal common extent of your rasters, and crop them all to that extent before stacking them together and applying the operation.Suppose you have three rasters:
A first way to do that:
Another one:
I am not too sure of what you exactly want, but if you really want to keep all your rasters complete (no
crop
operation), you could also compute the largest extent (same as the second method above, just invertmin
andmax
) andextend
all you rasters to that one before stacking them (same thing, you just end up with larger rasters, filled with NA's... not sure this is really desired):Does that help?
NOTE
You might not want to play with
setExtent()
orextent() <- extent()
, as you could end with wrong geographic coordinates of your rasters (i.e., the extent would be modified, but not the content, so you'd actually translate your rasters likely without aiming at that as the resulting overlap between them would be physically meaningless).