1

How to extract mean from a raster using extract function in R while considering raster cell values above 0?

I have multiple rasters with some negative cell values and no-data. I am able to ignore no data using na.rm = T. But don't know how to ignore negative cell values or apply greater than 0 threshold.

Below is my code:

library(rgdal)
library(raster)
setwd("E:/R_data")
pointg <- readOGR("E:/R_data","euro")
rasterfiles <- list.files(".", pattern = "tif")
for(j in 1:length(rasterfiles)){
  curRaster <- raster(paste("E:/R_data", rasterfiles[j], sep ="/"))
  csvDatatoWrite <- data.frame(pointg$Name, extract(curRaster, pointg, fun=mean, na.rm=TRUE))
  names(csvDatatoWrite)[2] <- substr(rasterfiles[j],1,7) 
  csvst <- csvDatatoWrite
  csvtrans <- t(csvst)
  write.table(csvtrans, file = "euro.csv", append = TRUE, sep = ",", row.names = TRUE, col.names = FALSE)
}
  • fwiw use cellFromXY to build the cell index once, not every time through the loop – mdsumner Aug 8 '17 at 22:47
1

If you want to ignore values lower than 0, you need to mask this values off. You can use mask with a logic test. I will create a dummy raster and points to apply extract:

library(raster)

set.seed(1)

r <- raster()
r <- setValues(r, rnorm(n = ncell(r)))

points <- SpatialPointsDataFrame(coords = data.frame(x=c(-100,0,100,-100,0,100),y=c(50,50,50,-50,-50,-50)),proj4string = r@crs,data=data.frame(ID=1:6))

I don't know why you want to calculate mean extracting values with points. When you extract by point, you get the value of the specific coordinate of that point. In the case of polygons or lines, the function is applied. But with your example:

extract(r,points,fun=mean,na.rm=T)
## [1] -0.8713186 -0.9070071  0.3098898  1.1223128 -1.8380112 -1.3434780

To omit those values, apply a mask selecting all value upper than 0. The result is a raster of 1 and 0, so use 0 as a mask value:

extract(mask(r,r>0,maskvalue=0),points,fun=mean,na.rm=T)
## [1]        NA        NA 0.3098898 1.1223128        NA        NA
1

You can subset rasters using [ ] notation, but note this returns a vector not a raster. So if all you are interested in is the mean and you don't actually want a raster with cells > 0 then all you need to do is

mean(r[r>0])

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.