I need to get multiple histograms from a tif image. I have the following data:

A big raster tif image:

tif1 <- raster("myRaster.tif")
hist(tif1, breaks= 10) # gives the entire histogram 

A shapefile of a country. This shapefile contains a polygon for each administrative area:

shp_np <- readOGR("NPL_adm2.shp")

I can think of a way to get the histogram by repetitively cropping raster tif using each Polygon in shapefile one by one. But, it is not efficient.

Now, I am searching for easy way to get the histogram information for each polygon in the shapefile.


1 Answer 1


You can use the extract function from the raster package to get the values for each polygon. That should be quicker than trying to use crop or mask for every polygon.

Alternatively,rasterize the polygons on the same basis as your raster. That gets you a raster with values from 1 to the number of polygons. You can then treat your rasters as R vectors and use tapply to apply a function to subsets of the raster.

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.