Wednesday, February 19, 2020

R Code to process vector to raster data fast

Use this R Code to convert and process vector to raster data fast.

Option 1 
# Load libraries
library('raster')
library('rgdal')
library('parallel') 

# Load a SpatialPolygonsDataFrame 
# Load shapefile
Data_sample <- system.file("external/lux.shp")
Data_sample2 <- shapefile(Data_sample) 

# Define RasterLayer object
r.raster <- raster()

# Define raster extent
extent(r.raster) <- extent(Data_sample2)

# Define pixel size
res(r.raster) <- 0.1
# Rasterize
system.time(Data_sample2.r <- rasterize(Data_sample2, r.raster)) 
Option 2
# Calculate the number of cores
num_cores <- detectCores() - 1

# Number of polygons features
features <- 1:nrow(Data_sample2[,])

# Split features in n parts
n <- 20
parts <- split(features, cut(features, n))

# Initiate cluster (after loading all the necessary object to R environment: Data_sample2, parts, r.raster, n)
cl <- makeCluster(num_cores, type = "FORK")
print(cl)

# Parallelize rasterize function
system.time(rParts <- parLapply(cl = cl, X = 1:n, fun = function(x) rasterize(Data_sample2[parts[[x]],], r.raster)))

# Finish
stopCluster(cl)

# Merge all raster parts and plot
Merge_parts <- do.call(merge, rParts)
plot(Merge_parts)

0 comments:

Post a Comment