Reputation: 569
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?
Upvotes: 0
Views: 78
Reputation: 102920
Maybe you can try the following code to see if it can work with larger dataset
OUT <- data.frame(x = MOD$Tas[apply(abs(outer(OBS$Lat+1i*OBS$Lon,MOD$Lat+1i*MOD$Lon,"-")),1,which.min)])
such that
> OUT
x
1 3
2 3
3 3
4 3
5 4
6 4
Upvotes: 1