Advertisement
Guest User

Untitled

a guest
Apr 16th, 2014
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. library(raster)
  2. dat = list()
  3. dat$x = seq(1.5, by = 10, len = 10)
  4. dat$y = seq(3.5, by = 10, len = 15)
  5. dat$z = matrix(sample(c(0,1), size = 10*15, replace = T), 10, 15)
  6.  
  7. r=raster(dat);plot(r)
  8.  
  9. r_poly = rasterToPolygons(r, fun = function(r) {r == 1}, dissolve = F)
  10. plot(r_poly, add = T)
  11.  
  12. b = extract(r,r_poly_new) # "r_poly_new" contains the combined polygons
  13. str(b) # list of clearly separated polygons
  14. tab = lapply(b,table)
  15. tab
  16.  
  17. library(rgeos) ## For the function gArea
  18.  
  19. ## Clump and polygonize
  20. Rclus <- clump(r)
  21. SPclus <- rasterToPolygons(Rclus, dissolve=TRUE)
  22.  
  23. ## Check that this works
  24. plot(SPclus, col = seq_along(SPclus))
  25.  
  26. ## Get cluster areas from RasterLayer object
  27. transform(data.frame(freq(Rclus)),
  28. area = count*prod(res(Rclus)))
  29.  
  30. ## Get cluster areas from SpatialPolygons object
  31. transform(data.frame(SPclus),
  32. area = gArea(SPclus, byid=TRUE))
  33.  
  34. ## Using gArea as above is better than the following, which gives misleading
  35. ## results for projected data. (See ?"Polygons-class" for explanation)
  36. ## h.t. Robert Hijmans & Roger Bivand in the R-sig-geo thread starting here
  37. ## https://stat.ethz.ch/pipermail/r-sig-geo/2013-December/020065.html
  38. transform(data.frame(SPclus),
  39. area = sapply(SPclus@polygons, function(X) X@area))
  40.  
  41. require(rgeos)
  42. uni <- gUnion( r_poly , r_poly )
  43. plot( uni , col = 2 )
  44.  
  45. m <- clump(r)
  46. f <- freq(m)
  47. f[,2] <- f[,2] * xres(r) * yres(r)
  48.  
  49. a <- area(r)
  50. zonal(a, m, 'sum')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement