[R-sig-Geo] efficient way to get values from a raster

Babak Naimi naimi at itc.nl
Fri Sep 21 13:59:01 CEST 2012


Dear list,

I want to extract cell values from a raster object given row and column numbers or cell numbers. The solution I used is not efficient (see the following) comparing with extracting values from a matrix. Any advice? 

> m <- matrix(rnorm(25),5) # matrix
> r <- raster(m) # raster

# --- case 1:
> system.time(for (i in 1:1000) r[1:3,1:3]) # extracting values from raster given rows and columns
user  system elapsed 
      0       0       0 

> system.time(for (i in 1:1000) m[1:3,1:3])  # extracting the same values from matrix
 user  system elapsed 
   8.41    0.03    9.58 

#---- case 2: 
> cells <- c(1,2,3,6,7,8,11,12,13) # cell numbers 

> system.time(for (i in 1:1000) r[cells]) # extracting values from raster given cells number
user  system elapsed 
   3.52    0.00    3.59 
> system.time(for (i in 1:1000) t(m)[cells]) # extracting the same values from matrix
user  system elapsed 
   0.07    0.00    0.08 

Best regards,
Babak


More information about the R-sig-Geo mailing list