0
votes

This might be one for gis.stackexchange but - I'm working with raster data, and attempting to extract values. The problem I'm running into is that my coordinates do not always overlap with the raster data (I have coordinates on the coastline, and sometimes the pixels are a wee bit offshore). I can use buffer, but, sometimes the results are inappropriate, as the buffer radius might, say, cause extract to cross a headland, getting data from pixels that have no relationship to the GPS coordinates I'm interested in.

Rather, I'd like to create a way to buffer directly to the east or west (or in some cases north/south) - to extract the value in the first pixel on a straight line from the coordinates I have.

Consider the following:

library(raster)
set.seed(pi)
# example data
r <- raster(ncol=36, nrow=18, crs='+proj=utm +zone=14 +datum=WGS84')
r[] <- 1:ncell(r)
r[sample(length(r), 250)] <- NA

xy <- cbind(x=-50, y=-15)

plot(r)
plot(SpatialPoints(xy), add=T, pch=19)
segments(-180, -15, 180, -15, lty=2)

which generates

map

If I just extract with a buffer of say, 50 meters...

extract(r, xy, buffer=50)
[[1]]
 [1] 227 228 229 230  NA 232  NA  NA 264 265  NA 267 268 269 297 298 299  NA  NA  NA 303  NA 305 306
[25]  NA 334 335 336 337 338 339  NA 341 342  NA  NA 371  NA  NA  NA  NA 376 377  NA 405 406 407  NA
[49]  NA 410 411 412 413 414  NA 442 443 444  NA  NA 447  NA  NA 450  NA 479  NA 481 482  NA 484  NA
[73]  NA 516 517 518  NA 520

(which, really, that should still get me an NA, as buffer is in meters...now I'm doubly confused - although that is not germane to this question)

How, then, could I extract the first value to the west or east along the dotted line, rather than use a circular buffer?

1
"which, really, that should still get me an NA, as buffer is in meters". Yes, but so is your coordinate reference system. So with 10 by 10 m cells, a 50 meter radius buffer should have many cells.Robert Hijmans
Huh. I thought they were larger. Apologies, I'm still fairly new to working with geospatial data, projections, and the like - thus I thought I had a larger cell size here. Is there a good CRS to cell size reference you'd recommend?jebyrnes

1 Answers

1
votes

Here is an approach

library(raster)
set.seed(pi)
r <- raster(ncol=36, nrow=18, crs='+proj=utm +zone=14 +datum=WGS84')
r[] <- 1:ncell(r)
r[sample(length(r), 250)] <- NA
xy <- cbind(x=-50, y=-15)

row <- rowFromY(r, xy[,2])
col <- colFromX(r, xy[,1])

left <- rev(na.omit(r[row, 1:col]))[1]
right <- na.omit(r[row, col:ncol(r)])[1]

left
##[1] 371
right
##[1] 376