How can I speed up the extraction of a fraction of the types of vegetation in a buffer from a raster?

I would like to receive spatial data in a 10 km buffer of about 30,000 objects of the SpatialLines class and calculate the proportion of each type of land cover around buffered lines. The first time I used the crop function to crop a raster. Then I used the extract function (raster package) to calculate the proportion of 10 types of vegetation cover. Here is my code:

 lapply(1:nrow(tab_lines), FUN=function(k){ 

First step: create a 10 km long buffer around the line

 buf_line <- gBuffer(seg_line[k], width=10000) ## seg_line = Lines objects 

Second step: extract the types of vegetation in the buffer from the raster

 ha <-extract(x=data_raster,y=buf_line) 

Third step: calculate the proportion of 10 types of vegetation cover

The proportion of each type of vegetation should be in columns (one column = one type of vegetation)

  ha_1 <-length(ha[[1]][ha[[1]]==1])/length(ha[[1]]) ha_2 <-length(ha[[1]][ha[[1]]==2])/length(ha[[1]]) ha_3 <-length(ha[[1]][ha[[1]]==3])/length(ha[[1]]) ha_4 <-length(ha[[1]][ha[[1]]==4])/length(ha[[1]]) ha_5 <-length(ha[[1]][ha[[1]]==5])/length(ha[[1]]) ha_6 <-length(ha[[1]][ha[[1]]==6])/length(ha[[1]]) ha_7 <-length(ha[[1]][ha[[1]]==7])/length(ha[[1]]) ha_8 <-length(ha[[1]][ha[[1]]==8])/length(ha[[1]]) ha_9 <-length(ha[[1]][ha[[1]]==9])/length(ha[[1]]) ha_10 <-length(ha[[1]][ha[[1]]==10])/length(ha[[1]]) return(cbind(ha_1, ha_2, ha_3, ha_4, ha_5, ha_6, ha_7, ha_8, ha_9, ha_10)) }) 

How to speed up processing time for 30,000 spatial lines? Are there any other packages in R that can provide faster processing of this type of extraction?

+6
source share
1 answer

Here is a shorter wording

 library(raster) library(rgeos) buf_line <- gBuffer(seg_line, width=10000, byid=TRUE) ha <- extract(x=data_raster, y=buf_line) h <- sapply(ha, function(x) tabulate(x, 10)) h <- h / colSums(h) 

But I don’t think it will be much faster. Instead of extracting, you can try sp::over

Depending on your computer, things may speed up the first time you start

 beginCluster() 
+5
source

All Articles