Skip to content

Reassigning coordinates?

4 messages · Roger Bivand, Barry Rowlingson, Brian

#
Hello List,
I need to reassign coordinates of a few points to have coordinates of 
the nearest raster cell. I KNOW that this is BAD practice but for the 
time being I  assume that it does not affect my analysis (species 
distribution analysis). I think the datum of the point data is different 
than that of my raster data, but for now it is not important.

I have already perused the "sp" and "raster" packages extensively.
I guess I just need to be pointed in the right (WRONG) direction. I had 
a few thoughts with the distance function but I am now stuck. Maybe use 
"distance" then "which.min" then take the coordinates?

Best Regards,
Brian
#
On Tue, 2 Nov 2010, Brian Oney wrote:

            
Maybe try nn2() in the RANN package with k=1 to find the nearest neighbour 
for each query point, with - I think - grid as data and points to move as 
query?

Roger

  
    
#
On Tue, Nov 2, 2010 at 10:00 AM, Brian Oney <zenlines at gmail.com> wrote:
If you have some points in a SpatialPointsDataFrame and a grid as a
SpatialPixelsDataFrame then you can do an overlay. So for example,
using 'm' from help(SpatialPixelsDataFrame) and 'pts' as some random
clicking points:

 > pts[1:10,]
        coordinates         zz
1  (179333, 330803) 0.76290682
2  (179600, 331026) 0.38275344
3  (180462, 331370) 0.75330357
...

 > overlay(m,pts)
 [1] 1930 1737 1434 1093 1115 1495 1705 2025 2146 2386 1780  728  487 1056 1256
[16] 1567 1778 1039  819 2465

 - gives the index in 'm' where each point in pts is, hence something like:
x        y      x      y
 [1,] 179332.9 330802.6 179340 330820
 [2,] 179599.7 331025.5 179580 331020
 [3,] 180461.9 331369.9 180460 331380
 [4,] 180533.7 331785.2 180540 331780
 [5,] 180010.3 331734.6 180020 331740

 gives the original and grid cell coordinates.

 something similar might work with package:raster objects...

Barry
#
Hello Barry and Roger,

Thank you for the suggestions.
I got the nn2() function to work and took the coordinates of the nearest 
non-NA raster cell and assigned them to the points. I forgot to mention 
that I have raster cells that are non-NA and some that are not and my 
point lay in the NA zone (just barely). In this case, I set k=6 to get 
all surrounding raster cells (because some  of the nearest cells still 
have an NA value) that selected the coordinate set from the raster cell 
whose nn distance to the next non-na cell was minimal.
It was dirty but it worked.

Thanks for the help,

Brian

# Code
# rast.coords are a subset of relevant coodinates from the center of 
relevant raster cells. 'pc.na' is the xy-matrix of the coordinates 
needing reassigning.
near <- data.frame(nn2(rast.coords, pc.nan, k=6))
na.near.cell1 <- near$nn.idx.2
reassign.coords <- xyFromCell(pc.clime, cell=na.near.cell)
# Put them where they belong and voile.
On 11/2/2010 1:21 PM, Barry Rowlingson wrote: