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

Babak Naimi naimi at itc.nl
Fri Sep 21 15:50:40 CEST 2012


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
________________________________________
From: b.rowlingson at gmail.com [b.rowlingson at gmail.com] On Behalf Of Barry Rowlingson [b.rowlingson at lancaster.ac.uk]
Sent: Friday, September 21, 2012 2:49 PM
To: Babak Naimi
Cc: r-sig-geo at r-project.org
Subject: Re: [R-sig-Geo] efficient way to get values from a raster

On Fri, Sep 21, 2012 at 12:59 PM, Babak Naimi <naimi at itc.nl> wrote:
> 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

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


> #---- 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

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



More information about the R-sig-Geo mailing list