Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. # Bring in data
  2. library(data.table)
  3. library(raster)
  4. set.seed(123)
  5.  
  6. # Bring in tifs and subset to your 16 states
  7. tifFiles <- list.files(".", pattern=".TIF$", full.names = TRUE)
  8. tifFiles <- paste0("./Suitability_Prob_v",c(30:39,310:315),".TIF")
  9.  
  10. # How many points do we want to sample from each state?
  11. # I am not sure what is in your csv file, so I sampled some points from a poisson
  12. sampPoints <- data.table(State=tifFiles, N=rpois(length(tifFiles),6))
  13.  
  14. # Function to read in raster and sample points
  15. readRasterAndSample <- function(rasFile, count) {
  16.  
  17. # Read in raster and deal with 0s and NAs
  18. ras <- raster(rasFile)
  19. ras[ras < 0] <- 0
  20.  
  21. # Convert to data.table
  22. rasDT <- as.data.frame(ras, xy=TRUE)
  23. setDT(rasDT)
  24. setnames(rasDT, c("x","y","values"))
  25.  
  26. # Sample non-zero points according to desired count
  27. # Use raster probability as sample prob
  28. outPoints <- rasDT[values > 0, .SD[sample(1:.N, size=min(count,.N), prob=values)]]
  29.  
  30. # Adjust points so they are the midpoint of the cellgrid
  31. outPoints[, x := x + 0.5*res(ras)[1]]
  32. outPoints[, y := y + 0.5*res(ras)[2]]
  33. outPoints[, state := basename(rasFile)]
  34.  
  35. # Combine into list and return
  36. outList <- list(ras=ras, pts=outPoints)
  37. return(outList)
  38. }
  39.  
  40. # Apply function to all states
  41. rasterList <- lapply(1:nrow(sampPoints), function(x)
  42. with(sampPoints[x], readRasterAndSample(rasFile=State, count=N)))
  43.  
  44. # Collect all rasters and merge
  45. rasterAll <- do.call(merge, lapply(rasterList, "[[", "ras"))
  46.  
  47. # Collect all state points and convert to SpatialPointsDataframe
  48. pointDat <- rbindlist(lapply(rasterList, "[[", "pts"), fill=TRUE)
  49. coordinates(pointDat) <- ~x+y
  50. proj4string(pointDat) <- rasterAll@crs@projargs
  51.  
  52. # Plot to check
  53. plot(rasterAll)
  54. plot(pointDat, add=TRUE)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement