[GIS] Calculate mean value for each raster and convert output array to data frame

rraster

How do I calculate mean value for each raster and convert output array to data frame?

r <- as.data.frame(cellStats(x,mean))

Best Answer

I believe that a call to "data.frame" is all you need. If you have several rasters, just stack them. If you want the rasters as columns and the statistic as rows you can just transpose on the fly (see second example)

library(raster)
x <- stack(system.file("external/rlogo.grd", package="raster")) 
( x.stats <- data.frame(x.mean=cellStats(x, "mean")) )

# Combine multiple statistics as rows
( x.stats <- t(data.frame(x.mean=cellStats(x, "mean"))) )
( x.stats <- rbind(x.stats, t(data.frame(x.sd=cellStats(x, "sd")))) )