I have a dataframe with Longitudes and Latitudes and I would like to create a 0.5x0.5 degrees grid that shows which lat, long fall within it. So far, I have tried several solutions, including some found here on stackoverflow, that use cut
and expand.grid
as well as code that uses the package "sp" but none has worked out for me (maybe I simply can't implement them).
Any suggestions on how I can group my data into a 0.5x0.5 degrees grids?
Latitude | Longitude |
---|---|
31.602 | -39.848 |
31.675 | -39.467 |
31.747 | -39.083 |
32.152 | -36.795 |
32.218 | -36.408 |
32.285 | -36.022 |
32.348 | -35.635 |
32.412 | -35.247 |
32.475 | -34.858 |
32.535 | -34.47 |
32.595 | -34.082 |
32.677 | -33.707 |
32.763 | -33.323 |
Thank you all for your time and effort.
Edit: My best effort was this snippet
library(tidyverse)
pos <- dassem %>%
dplyr::select(Latitude, Longitude)
gridx <- seq(from = min(dassem$Longitude), to = max(dassem$Longitude), by = 2)
gridy <- seq(from = min(dassem$Latitude), to = max(dassem$Latitude), by = 2)
xcell <- unlist(lapply(pos$Longitude,function(x) min(which(gridx>x))))
ycell <- unlist(lapply(pos$Latitude,function(y) min(which(gridy>y))))
pos$cell <- (length(gridx) - 1) * ycell + xcell
pos
# A tibble: 45,647 x 3
Latitude Longitude cell
<dbl> <dbl> <dbl>
1 51.7 -54.9 638
2 51.9 -54.5 638
3 52.1 -54.1 638
4 52.3 -53.7 639
5 52.5 -53.2 639
6 52.7 -52.8 639
7 52.9 -52.4 639
8 53.2 -52.0 639
which, as you can see, does not return a 2x2 degrees grid (I set it to 2x2, and not 0.5x0.5).