h7681
h7681

Reputation: 355

R - Convert latitude and longitude to grid numbers

I'm currently doing a classification project and the data I'm using includes lat/long attributes. In order to simply the model(s) I'm thinking it might be easier to replace the raw coordinates with a single column of 'grid' numbers.

By this I mean chop-up the area that the coordinates cover into an arbitrary number of grid points, number each square within the grid, and then replace the lat/long figures with the grid number which they fall in. For example, a 9 square grid might look like this:

123
456
789

I've done a fair bit of searching on here and Google and can't seem to find a solution. The closest I can find is the Universal Transverse Mercator coordinate system (which some R packages support), but the squares within this grid are too large. I'd like to be able to set the size of the grid myself.

I'm at a bit of a loss, and was wondering if the kind people of this forum knew of any R packages or techniques to achieve what I'd like. I'll append an example of my lat/long columns. Thanks.

Latitude    Longitude
41.95469    -87.800991
41.95469    -87.800991
41.994991   -87.769279
41.974089   -87.824812
41.974089   -87.824812
41.9216     -87.666455
41.891118   -87.654491
41.867108   -87.654224
41.867108   -87.654224
41.896282   -87.655232
41.919343   -87.694259

Upvotes: 0

Views: 1834

Answers (1)

dww
dww

Reputation: 31452

Not especially elegant, but this works

pos <- data.frame(lat=c(
41.95469,
41.95469,    
41.994991,   
41.974089,   
41.974089,   
41.9216,     
41.891118,   
41.867108,   
41.867108,   
41.896282,   
41.919343),   
long=c(
-87.824812,
-87.769279,
-87.800991,
-87.800991,
-87.824812,
-87.666455,
-87.654491,
-87.654224,
-87.654224,
-87.655232,
-87.694259))

gridx <- seq(from=-87.9,to=-87.6,by=0.01)
gridy <- seq(from=41.8,to=42,by=0.01)
xcell <- unlist(lapply(pos$long,function(x) min(which(gridx>x))))
ycell <- unlist(lapply(pos$lat,function(y) min(which(gridy>y))))
pos$cell <- (length(gridx) - 1) * ycell + xcell

Upvotes: 1

Related Questions