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

r <- as.data.frame(cellStats(x,mean))
  • I actually made a raster stack, 's <- as.data.frame(cellStats(r,mean))'thanks @atmycpu. Now I only need the stats to be done on values ranging from -1 to 1. – jmutua Jun 30 '16 at 8:29

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)

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")))) )

to loop through a list of raster file paths:

library(raster) #load raster package

rasterlist <- list("path 1","path 2",...) #create list of raster file paths
outlist <- list() #create empty list to store outputs from loop

for (i in 1:length(rasterlist)) { #for each raster in rasterlist
   r <- raster(rasterlist[[i]]) #read element i of rasterlist into R
   val <- getValues(r) #get raster values
   m <- mean(val,na.rm=T) #remove NAs and compute mean
   outlist[[i]] <- c(rasterlist[[i]],m) #store raster path with mean

df <- data.frame(do.call(rbind,outlist)) #convert list to data frame
colnames(df) <- c("raster path","mean")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.