2

R: finding line in matrix with points close to two selected points.

I have a matrix with long/lat for an area. And I have a point in this area with a longitude and latitude, so I need to find the point in the matrix that is the best match.

I have tried this, but it is not working:

find.point <- is.numeric(which(abs(matrix[,1]-East)==min(abs(matrix[,1]-East))) 
                               && which(abs(matrix[,2]-North)==min(abs(matrix[,2]-North))))

How to find the point where East is closest to matrix[,1] and also North closest to matrix[,2]?

Sotos
  • 51,121
  • 6
  • 32
  • 66
Anne
  • 21
  • 1
  • 3
  • 2
    Welcome to Stack Overflow. Please post a reproducible example along with expected output. Take a look [at this link](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more information. – Sotos May 06 '16 at 09:45
  • You need a definition of 'what is the nearest point' (euclidean distance or sum of the abolute differences for `North` and `East` or other metric). Calculate the this distance for each point, then you can use `which.min()` – jogo May 06 '16 at 09:51

1 Answers1

7

Without some concrete data from you, it is somewhat hard to help you exactly. But assuming you want to compute the nearest point with the Euclidean distance and that your data is somewhat similar to below, this may illustrate how you can do it:

# Create some toy data
set.seed(1)
pos <- matrix(runif(20), 10, 2)
colnames(pos) <- c("lon", "lat")
print(pos)
#             lon       lat
# [1,] 0.26550866 0.2059746
# [2,] 0.37212390 0.1765568
# [3,] 0.57285336 0.6870228
# [4,] 0.90820779 0.3841037
# [5,] 0.20168193 0.7698414
# [6,] 0.89838968 0.4976992
# [7,] 0.94467527 0.7176185
# [8,] 0.66079779 0.9919061
# [9,] 0.62911404 0.3800352
#[10,] 0.06178627 0.7774452

new.pos <- c(0.5, 0.5) # New position

# Compute distance to points and select nearest index
nearest.idx <- which.min(colSums((t(pos) - new.pos)^2))
nearest.idx
#[1] 9

# Pick out the point
pos[nearest.idx, ]
#      lon       lat 
#0.6291140 0.3800352 

The line that computes the distances relies on two facts: 1) matrices in R are store in a column-major order and 2) R's reuse/repeat rules when the vector is too short.

Anders Ellern Bilgrau
  • 9,928
  • 1
  • 30
  • 37