Skip to content
Prev 27742 / 29559 Next

Isolating only land areas on a global map for computing averages

Rain--
Yes, it is possible to do it with your extant raster stack.  In fact,
pretty much all reasonable approaches will do that.  Anything you do will
create a raster layer with values at every one of your 8192 raster cells:
some values will be 0 or NA.

The trivial answer if you only had a small range of latitude, and small
raster cell sizes relative to your polygon, would be the
raster::rasterize() function to generate a raster mask.

But, with a global raster from +90 to -90, any interpretable answer
averaging over area needs to take into account the different area of a grid
cell at 70 deg latitude vs 0 deg.  See:
https://gis.stackexchange.com/questions/29734/how-to-calculate-area-of-1-x-1-degree-cells-in-a-raster
At that point, you should go ahead and account for fractions of grid cells
over land so your averaging would be over land area.

I'm reticent to give you a complete code solution because without a name,
you may well be a student with this as an assignment.  But, my approach
would be:

create a SpatialPolygonsDataFrame object "gridPoly" from any of your raster
layers via raster::rasterToPolygons()
generate an id value for each of those polygons as row & column indices
from the raster, or as the cell number.
get land polygon SpatialPolygons object "landPoly" with polygons of land
only, not ocean.
create a new SpatialPolygons object from gIntersect::gridPoly, landPoly,
byid = c(TRUE, FALSE))
calculate an area of each polygon in that object via
geosphere::areaPolygon()  {rgeos::gArea()  only works for projected CRS}
create your mask/weights raster layer with either all NA or all 0.
either:
     parse the id values to row & column values.
     use the triplets of row, column, and area to replace the corresponding
NA or 0 values in that mask
or:
     if you used cell numbers, just use the cell numbers and area values in
replacement in that mask

create a second weight raster via raster::area() on one of your raster
layers.
raster multiply your polygon-area and your raster::area values to give the
actual weighs to use.

This still is an approximation, but likely +/- 1-2%.

If this is still complete gibberish to you, either I need more coffee or
you need to consult a good reference on working with spatial data in
general.
On Thu, Nov 7, 2019 at 8:25 AM <rain1290 at aim.com> wrote: