[R-sig-Geo] How to extract values from adjacent raster cells that are not touched by SpatialLines?
Santiago Sánchez
santiago.snchez at gmail.com
Sat Aug 19 20:52:13 CEST 2017
Hi Andre,
I'm not completely sure if this is what you are looking for, but here is a
worked example on how to get cell indices (thus, data) from neighbouring
cells. Essentially, I'm using the adjancency() function from raster,
reducing to unrepeated cells, and excluding the ones that fall under a line
object.
library(raster)
r <- raster(ncol=10,nrow=10) # generate a raster object
r[] <- 0 # populate values with 0's
p <- rasterToPolygons(r) # get a polygon for each cell (for visual purposes)
# make a line object (SpatialLines)
x <- c(-124.66110, -93.04031, -52.37858, 24.44486, 15.98469, 52.12075,
88.49592)
y <- c(-46.021148, -27.197684, -6.804443, 10.113111, 28.375197, 8.851744,
-12.463264)
xy <- data.frame(cbind(x,y))
spl <- SpatialLines(list(Lines(list(Line(xy)), ID=1)))
# get adjacent cells
lcells <- cellFromLine(r, spl)[[1]] # cells from line
r[lcells] <- 1 # mark line cells with 1
ad <- adjacent(r, lcells, 4) # this gives you a matrix with adjacent cells,
# you can specify 8 or 16
neighbouring cells,
# here I'm using 4
# sorting and removing duplicates
ad <- sort(as.vector(ad))
ad <- ad[!duplicated(ad)]
ad2 <- ad[ ! ad %in% lcells ]
r[ad2] <- 2
# to visualize the example:
plot(r)
plot(p, add=T)
plot(spl, add=T, col="red")
# Obviously, you con extract the values of adjacent cells simply with:
r[ad2]
[1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Hope this helps,
Santiago
--
==========================
Santiago Sanchez-Ramirez, PhD
Postdoctoral Associate
Ecology and Evolutionary Biology
University of Toronto
==========================
[[alternative HTML version deleted]]
More information about the R-sig-Geo
mailing list