Search code examples
rrastertiff

How to compute land cover values from another raster?


I have two rasters:

raster1
class      : RasterLayer 
dimensions : 2803, 5303, 14864309  (nrow, ncol, ncell)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : 60.85, 105.0417, 15.95833, 39.31667  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
source     : memory
names      : npp 
values     : -0.345, 1.723  (min, max)

raster2
class      : RasterLayer 
dimensions : 2803, 5303, 14864309  (nrow, ncol, ncell)
resolution : 0.008333333, 0.008333333  (x, y)
extent     : 60.85, 105.0417, 15.95833, 39.31667  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
source     : C:/a/b/Documents/c/landuse.tif 
names      : landuse
values     : 1, 12  (min, max)
attributes :
       ID                          zn
 from:  1 evergreen needleleaf forest
  to : 12                   croplands

raster2 is a land cover types of a specific region and raster1 is values of net primary productivity. I would like to compute how much net primary productivity is in each land cover class in raster 2. How could I achieve this in R?


Solution

  • Find the sum of the values of the cells in r1 for each land cover code in r2, output returned as a list. Could instead use lapply.

    
    library(raster)
    
    #Generate example data
    raster1 <-  raster(matrix(c(1,1,1,2,3,4,5,6,7),ncol =3))
    
    raster2 <- raster(matrix(c(1,1,1,2,2,2,3,3,3),ncol =3))
    raster2 <- as.factor(raster2)
    
    rat <- levels(raster2 )[[1]]
    rat[["landcover"]] <- c("land","ocean/lake", "rivers")
    levels(raster2 ) <- rat
    
    #Extract sum of values of raster 1 for each level of raster 2
    Val <- list()
    for(lc in levels(raster2)[[1]]$ID){
      Values <- raster1[raster2[]==lc]
    
      Val[[lc]] <- sum(Values)
    }