5

Is there a quick way in R to do summary statistics on a raster based on latitudinal intervals or bins. Not a summary of the entire raster layer but spatial subsections. For example, get the mean and sd of raster cell values for every two degrees in latitude.

Below is some example data of a projected raster with Lat/Long coordinates.

set.seed(2013)
library(raster)

r <- raster(xmn=-110, xmx=-90, ymn=40, ymx=60, ncols=40, nrows=40)
r <- setValues(r, rnorm(1600)) #add values to raster
r[r > -0.2 & r < 0.2] <- NA #add some NA's to resemble real dataset
plot(r)

> r
class       : RasterLayer 
dimensions  : 40, 40, 1600  (nrow, ncol, ncell)
resolution  : 0.5, 0.5  (x, y)
extent      : -110, -90, 40, 60  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       : layer 
values      : -3.23261, 2.861592  (min, max)
alistaire
  • 42,459
  • 4
  • 77
  • 117
Flammulation
  • 336
  • 2
  • 16

2 Answers2

2

Since your raster's resolution is 0.5 and you have 40 rows, you want the mean / sd for every 4 rows:

set.seed(2013)
library(raster)

r <- raster(xmn=-110, xmx=-90, ymn=40, ymx=60, ncols=40, nrows=40)
r <- setValues(r, rnorm(1600)) #add values to raster
r[r > -0.2 & r < 0.2] <- NA #add some NA's to resemble real dataset

rmean <- sapply(seq(1,nrow(r),4),function(rix) mean(r[rix:rix+3,],na.rm=T))

rsd <- sapply(seq(1,nrow(r),4),function(rix) sd(r[rix:rix+3,],na.rm=T))


# > rmean
# [1] -0.033134373 -0.180689704  0.176575934 -0.003422832 -0.049113312  0.234891614  0.188559162 -0.026514169  0.106970362
# [10]  0.096033677

So you're basically indexing the raster as matrix, only using the slices needed for mean / sd. For iteration you could also use lapply, which puts everything in a neat list.

Val
  • 6,585
  • 5
  • 22
  • 52
1

You can aggregate your rows (groups of 4 in this case) and columns (into one column)

a <- aggregate(r, c(ncol(r), 4), fun=mean)
b <- aggregate(r, c(ncol(r), 4), fun=sd)

lat <- yFromRow(a, 1:nrow(a))
plot(lat, values(a))
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63