0
votes

I have a raster image (.tif) with continuous values in each pixel between 0 and 1. I want to calculate the area (can be a number of pixels too) in this raster which has values in a set of value intervals: i.e. 0.1 - 0.2, 0.3 - 0.4, 0.7 - 0.8. The ultimate goal is to see which interval occupies a larger area. Any ideas which functions to try or how to approach it in R?

2
What do you mean by raster? The raster package, or just a matrix, or?mdsumner
Ok, see raster package, you can do direct comparisons, try table(values(cut(r, intervals))) but otherwise explore related functionality if you have not used raster yet.Use r= raster("file.tif") to read your filemdsumner

2 Answers

8
votes

If ras is your raster image, you can do the following:

sum(ras[] >= 0.1 & ras[] <= 0.2)

This returns the number of pixels that contain values within the range 0.1 - 0.2. If you multiply this by the squared cell size:

sum(ras[] >= 0.1 & ras[] <= 0.2) * res(ras)[1]^2

you get the area in square meters.

Simply change the values to adjust the range, or write a function / loop that iterates over predefined value ranges and maybe even creates a barchart.

Something like:

intervals <- list(c(0.1,0.2), 
                  c(0.2,0.3),
                  c(0.3,0.4))

sapply(intervals, function(x) { 
  sum(ras[] > x[1] & ras[] <= x[2])
})
1
votes

Since I couldn't find any function that does what I needed I programed this simple one to calculate the area in hectares covered by a certain pixel value in a raster. The default value is set to 1, very useful when working with binary masks, but can be changed with argument 'clas'. It's writen in spanish, but the warning says "class not present in the classification" (I work with supervised classifications).

area.r<-function(x,clas=1){

  '%ni%'<-Negate('%in%')
  if(clas%ni%unique(x)){return(print("clase no presente en la clasificación"))} else 
    {
      area<-length(x[x%in%clas])*(res(x)[1]^2/10000)
      return(area)
    }    
}