Find point on grid in R?

Viewed 101

A similar question was asked here. However, the solution doesn't seem to work for me. I am trying to find the grid reference for a given point. For example, if I have a grid and a point that looks like this: grid

We can see that my point is in grid reference: (53.0, -7). So, in my data, I have a data frame of points that I want to find the grid reference for. For example, if my data looks like this:

 # data frame of points I want to find on the grid
    df1 <- data.frame(place = paste0("p", 1:10),
                      lon = c(-6.855823,-6.200411,-6.452618,-7.638343,-7.810404,-7.810404,-6.739738,-6.108979,-8.585729,-7.325793),
                      lat = c(53.38225,53.16652,53.05181,53.04949,52.16302,52.16302,53.46026,53.13494,52.31639,53.34612))
set.seed(22)
# data frame containing the grid
df2 <- data.frame(lon = rep(seq(-8.5, -6.5, 0.1), 16),
                  lat = rep(seq(52,53.5, 0.1), each = 21),
                  var = rnorm(16*21))

What Im trying to do is select the var in df2 that corresponds to the grid reference for each of my points in df1

For clarity, if I take the point df1[1,] we have:

place       lon      lat
1    p1 -6.855823 53.38225

This corresponds to row 291 in df2. Then once, I have the row, I want to get the var value for that row.

Any suggestions as to how I could do this?

Additionally, in my real data df2 has about 5 figures after the decimal point... don't know if this makes a difference, but I thought I should mention it.

2 Answers

I eventually found a good solution here. I adapted the answer given by the user @eddi to my data and it seems to work well. Just thought I should provide this information for anyone else having accuracy issues like I was.

One way of doing this is to join the two dataframes. The issue is the exactness of the match. In this case I have rounded df1's lon and lat columns to 1 decimal place to match the accuracy of df2. If df2, is 5 d.p. then there may not be exact matches. Even with this accuracy, not all rows of df1 are found in df2 - The "NA"s in the var column.

A solution:

library(tidyverse)

df1 %>% 
  mutate(across(lon:lat, ~ round(., 1))) %>% 
  left_join(df2, by = c("lon", "lat"))

   place  lon  lat         var
1     p1 -6.9 53.4  0.99791722
2     p2 -6.2 53.2          NA
3     p3 -6.5 53.1 -0.18539765
4     p4 -7.6 53.0 -0.06516846
5     p5 -7.8 52.2  1.07760433
6     p6 -7.8 52.2  1.07760433
7     p7 -6.7 53.5  0.40551060
8     p8 -6.1 53.1          NA
9     p9 -8.6 52.3          NA
10   p10 -7.3 53.3 -0.63281293
Related