[R] getting data associated with coordinates in a spatial data frame

jon.skoien at jrc.ec.europa.eu jon.skoien at jrc.ec.europa.eu
Fri Oct 14 13:31:24 CEST 2011


On 13-Oct-11 20:33, Sarah Goslee wrote:
> Hi,
>
> On Thu, Oct 13, 2011 at 2:05 PM, Bailey, Daniel<bailed at spu.edu>  wrote:
>> Thank you Sarah. I tried your suggestion, and if I coerce it into a normal data.frame, that method works. But if you've already made the data into a SpatialPixelsDataFrame and run coordinates (both from the package "sp") so that the columns "x" and "y" become a single column "coordinates" with the format (0, 17) for x and y, how do you then call or manipulate data at a specific location?
>>
>> The following:
>> e[e$coordinates==(0,17),]
>> Doesn't work.
> They "don't become a single column" but rather a single matrix with
> two columns, and (0, 17) isn't the correct way to specify a vector.
> You can identify particular coordinates using the form I offered
> earlier, and then use that to subset the data slot of your SGPF.
>
> Using built-in data:
>
> library(sp)
> data(meuse.grid)
> m = SpatialPixelsDataFrame(points = meuse.grid[c("x", "y")], data = meuse.grid)
> m at data[coordinates(m)[,"x"] == 181100&  coordinates(m)[,"y"] == 333660,]
>
> There ought to be a more elegant way to match coordinates (other than
> the do.call() and paste() approach), but I'm not sure what it is.

Not sure if it is nicer, but another possibility is:
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
meuse.grid at data[which(duplicated(rbind(c(181100, 333660), 
coordinates(meuse.grid))))-1,]  = factor(c(1,2,3,4,1))

To avoid numerical problems, you can also find the data of the location 
closest to the point you are interested in:
meuse.grid at data[which.min(spDistsN1(meuse.grid, c(181100, 333660))),] = 
factor(c(1,1,1,1,1))

For questions about spatial data you can also use the mailing-list 
r-sig-geo.

Cheers,
Jon



More information about the R-help mailing list