[R-sig-Geo] Problem with cell numbers when using a raster extent object

Robert J. Hijmans r.hijmans at gmail.com
Mon Nov 25 19:04:10 CET 2013


Ned,

Hard to see what does not work here. Perhaps it is just the [i] in
xyFromCell(predImage, sampleCells[i])?
Can you please provide a self-contained example, perhaps based on the below?

library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
e <- extent(r) + 100
s <- sampleRandom(r, size=100, cells=TRUE, extent=e)[,1]
xy <- xyFromCell(r, s)

plot(e)
plot(r, add=T, legend=F)
points(xy)



On Mon, Nov 25, 2013 at 9:42 AM, Ned Horning <horning at amnh.org> wrote:
> Hi -
>
> I have a script that calculates a common extent between two images than then
> uses the resulting extent to restrict the random selection of cells from a
> raster using the “sampleRandom” function. I use the following function:
>
> sampleCells <- sampleRandom(predImage, size=numSamps, cells=TRUE,
> extent=commonExt)[,1]
>
> Next I use "xyFromCell(predImage, sampleCells[i])" to calculate the
> coordinates of the center of a cell and all of the cell centers fall outside
> of the extent that I am using. Using "sp=TRUE" I get a similar result - all
> of the points are outside of the extent:
>
> sampleCells <- sampleRandom(predImage, size=numSamps, sp=TRUE,
> ext=commonExt)
>
> To get around this problem I tried to physically clip the image before
> running “sampleRandom” and the results are similar. The following line also
> produces cells that are outside of the extent “commonExt” when I use
> “xyFromCell”:
>
> sampleCells <- sampleRandom(crop(predImage,commonExt), size=numSamps,
> ext=commonExt, na.rm=TRUE)
>
> However, if I run the following line using"clip" and "sp=TRUE" the sample
> points fall within the extent:
>
> sampleCells <- sampleRandom(crop(predImage,commonExt), size=numSamps,
> sp=TRUE, ext=commonExt, na.rm=TRUE)
>
> So, there is a work-around but I'd prefer not to have the overhead of
> clipping the image.
>
> This seems somewhat similar to a problem I reported a few months ago and was
> fixed. Can anyone replicate this problem? Am I doing something wrong?
>
> I am using R version: 3.0.2 and Raster package version: 2.1-49 on Ubuntu
> 12.04 64 bit
>
> Ned
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list