[R-sig-Geo] find cells of a raster lying on a ring

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri Jul 13 11:13:48 CEST 2012


On Fri, Jul 13, 2012 at 1:25 AM, Lorenzo Cattarino
<l.cattarino at uq.edu.au> wrote:
> Hi R users,
>
> I would like to be able to calculate how many cells of a raster, and their values (1 or 0), lie at a distance r from a particular cell in the raster. In other words, I need to calculate the number and values of the cells lying on a ring with radius r and centred in x0 and y0.
>
> This is as far I got:
>
>
>
> require(spatstat)

 stop there!

 You might want to use the raster package, especially if you are using
geo-referenced data:

 > library(raster);library(sp)
 > z = raster(matrix(runif(10000),100,100))
 > projection(z)="+init=epsg:4400"
 > pt = cbind(.2,.6)
 > zd = distanceFromPoints(z,pt)
 > circ = zd>.4 & zd<.41
 > plot(circ)

 Note the circle is here computed as all grid cells within .4 and
.4+cell size distance. Then you can easily get the values in z that
correspond to circ==TRUE...

 > summary(z[circ])
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
0.002594 0.230600 0.479600 0.475500 0.690800 0.985400

 Another way would be to rasterize a circular line:

 > cline = cbind(.2+.4*sin(seq(0,2*pi,len=100)),.6+.4*cos(seq(0,2*pi,len=100)))
 > L = SpatialLines(list(Lines(Line(cline),"C")))
 > plot(z)
 > plot(L,add=TRUE)
 > LR = rasterize(L,z)
 > plot(LR)
 > plot(L,add=TRUE)

 but this is a bit slower, and slightly different:

 > summary(z[LR])
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
0.003472 0.239600 0.474300 0.476800 0.692900 0.997500

Barry



More information about the R-sig-Geo mailing list