Skip to content

efficient way to get values from a raster

2 messages · Barry Rowlingson, Babak Naimi

#
On Fri, Sep 21, 2012 at 12:59 PM, Babak Naimi <naimi at itc.nl> wrote:
I get practically the opposite, which is what I was expecting:

 > m <- matrix(rnorm(25),5) # matrix
 > r <- raster(m) # raster
 > system.time(for (i in 1:1000) r[1:3,1:3])
    user  system elapsed
   3.828   0.176   4.001
 > system.time(for (i in 1:1000) m[1:3,1:3])
    user  system elapsed
   0.004   0.000   0.002

 - much faster for a matrix than a raster. Raster package version: 1.9-94
Broadly similar this time:

 > system.time(for (i in 1:1000) r[cells])
    user  system elapsed
   1.436   0.000   1.438
 >  system.time(for (i in 1:1000) t(m)[cells])
    user  system elapsed
    0.04    0.00    0.04

 - matrix faster, as I expected.

 So I guess we now have two questions:

 1. Why is your raster extraction r[1:3,1:3] so much faster than
matrix extraction?
 2. How can you do raster extraction faster?

If this is a real problem in your code (ie extraction is taking >50%
of the time of whatever it is you are doing) then why not convert to
matrix first?

Barry
#
Dear Barry,

Sorry, it was my mistake to paste the results into the email!! Indeed, I also got the same results as you did. The reason that I am looking for an efficient way to extract data from raster, is that using raster dataset it is possible to write memory-safe functions.

Best,
Babak