I have two matrices as follows:
OBS = matrix(data=c(0.5, 1.0, 1.5, 2.0, 2.5, 3.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
3, 4, 2, 4, 3, 5),
nrow=6, ncol=3)
colnames(OBS)=c("Lat", "Lon", "Tas")
OBS = data.frame(OBS)
MOD = matrix(data=c(1.5, 3.0, 0.0, 0.0, 3, 4), nrow=2, ncol=3)
colnames(MOD)=c("Lat", "Lon", "Tas")
MOD = data.frame(MOD)
I want to use the coordinates in OBS and search for the closest set of coordinates from MOD and return the corresponding Tas values. The output should therefore be:
OUT = data.frame(c(3, 3, 3, 3, 4, 4))
I have applied the following solution:
library(geosphere)
# create distance matrix
mat <- distm(OBS[,c('Lon','Lat')], MOD[,c('Lon','Lat')],
fun = distVincentyEllipsoid)
# Find shortest distance in matrix and assign tas values from MOD
OUT <- MOD$Tas[max.col(-mat)]
This works fine for this example, but if you try with datasets with several hundred or more rows then it no longer works. Anyone know why?