I have various raster files. I am using following code in R to calculate mean of all the cell values of a raster file. For some rasters, it is giving NA value, however the rasters do have the data.

What could be the reason for this and how can I resolve it?

ff = list.files(path="F:/Test1/", pattern=".tif$", full.names=TRUE)
rl = lapply(ff, function(x) rast(x))
means1 = lapply(rl, function(x) global(x, 'mean'))
means2 = do.call(rbind.data.frame, means1)

write.csv(means2, 'F:/Test1/avg.csv')

2 Answers 2


Try adding na.rm=TRUE to accommodate NAs in your raster.

means1 = lapply(rl, function(x) global(x, 'mean', na.rm=TRUE)) 

If your rasters have the same extent and resolution you can simplify this to

r <- rast(ff)
global(r, "mean", na.rm=TRUE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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