[R-sig-Geo] efficient way to get values from a raster
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Fri Sep 21 14:49:16 CEST 2012
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