[R-sig-Geo] Drawing lines in raster cells

Oscar Perpiñán Lamigueiro oscar.perpinan at gmail.com
Sun May 12 16:23:45 CEST 2013


Hi Lionel,

With this code you will draw lines connecting raster cells with a
certain value. I am not sure if you also need to build a SpatialLines
object with them (which you won't get with my code):

library(raster)
library(latticeExtra) ## to use +.trellis and layer()

r1<-raster(ncols=10,nrows=10)
r1[]<-sample(0:1,100,replace=TRUE)

## extract coordinates of those cells with a condition
myCells <- Which(r1==1, cells=TRUE)
xy <- xyFromCell(r1, myCells)

## border and border.lwd are only needed to highlight the cells boundaries
spplot(r1, at=c(0, 0.5, 1), border='black', border.lwd=0.3) +
    layer(llines(xy, type='b', col='black'))


Best,

Oscar.

Lionel <s6lihert at uni-bonn.de> writes:

> Dear List,
>
> I would like to draw lines in raster cells with a certain values, I can 
> work around this with a for loop but as always this solution only works 
> for small datasets (which is not my case), I would therefore like to 
> have your opinion on this;
>
> #the code
> library(maptools) #to use spRbind
> out<-NULL
> r1<-raster(ncols=10,nrows=10)
> r1[]<-sample(0:1,100,replace=TRUE)
> for(i in 1:ncell(r1)){
>    if(r1[i]==1){
> lines<-SpatialLines(list(Lines(list(Line(matrix(c(xyFromCell(r1,i)+(res(r1)/2),xyFromCell(r1,i)-(res(r1)/2)),ncol=2,byrow=TRUE))),ID=as.character(i))))
>      if(is.null(out)){
>        out<-lines }
>         else {out<-spRbind(out,lines)}
>      }
>    print(i)
> }
>
> Thank you in advance,


-- 
Oscar Perpiñán Lamigueiro
Grupo de Sistemas Fotovoltaicos (IES-UPM)
Dpto. Ingeniería Eléctrica (EUITI-UPM)
URL: http://procomun.wordpress.com
Twitter: @oscarperpinan



More information about the R-sig-Geo mailing list