Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(raster)
- dat = list()
- dat$x = seq(1.5, by = 10, len = 10)
- dat$y = seq(3.5, by = 10, len = 15)
- dat$z = matrix(sample(c(0,1), size = 10*15, replace = T), 10, 15)
- r=raster(dat);plot(r)
- r_poly = rasterToPolygons(r, fun = function(r) {r == 1}, dissolve = F)
- plot(r_poly, add = T)
- b = extract(r,r_poly_new) # "r_poly_new" contains the combined polygons
- str(b) # list of clearly separated polygons
- tab = lapply(b,table)
- tab
- library(rgeos) ## For the function gArea
- ## Clump and polygonize
- Rclus <- clump(r)
- SPclus <- rasterToPolygons(Rclus, dissolve=TRUE)
- ## Check that this works
- plot(SPclus, col = seq_along(SPclus))
- ## Get cluster areas from RasterLayer object
- transform(data.frame(freq(Rclus)),
- area = count*prod(res(Rclus)))
- ## Get cluster areas from SpatialPolygons object
- transform(data.frame(SPclus),
- area = gArea(SPclus, byid=TRUE))
- ## Using gArea as above is better than the following, which gives misleading
- ## results for projected data. (See ?"Polygons-class" for explanation)
- ## h.t. Robert Hijmans & Roger Bivand in the R-sig-geo thread starting here
- ## https://stat.ethz.ch/pipermail/r-sig-geo/2013-December/020065.html
- transform(data.frame(SPclus),
- area = sapply(SPclus@polygons, function(X) X@area))
- require(rgeos)
- uni <- gUnion( r_poly , r_poly )
- plot( uni , col = 2 )
- m <- clump(r)
- f <- freq(m)
- f[,2] <- f[,2] * xres(r) * yres(r)
- a <- area(r)
- zonal(a, m, 'sum')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement