Here are two solutions, one of which is partially vectorized, which uses sapply , and I think the other is fully vectorized, but I wrote a couple of functions for the part of vector computing, so there may be a better way.
I also used them only for nobs1 = 4, 40 & 400 and nobs2 = 5, 50 & 500 , since my laptop is fighting for memory with large matrices .
The solution is sapply
R <- 6371 # Earth mean radius [km] delta.lon <- sapply(mylon2, "-", mylon1) delta.lon <- sin(delta.lon/2)^2 coslat2 <- cos(mylat2) coslat1 <- cos(mylat1) delta.lan <- sapply(mylat2, "-", mylat1) delta.lan <- sin(delta.lan/2)^2 a <- delta.lan + t(sapply(coslat1, "*", coslat2) * t(delta.lon)) b <- ifelse(sqrt(a)<1,sqrt(a),1) c <- asin(b) d <- 2 * c e <- R * d f <- c(t(e))
And to check the conclusion
sum(f) sum(mydistance) all.equal(f, mydistance) > sum(f) [1] 647328856 > sum(mydistance) [1] 647328856 > all.equal(f, mydistance) [1] TRUE
Solution - with features
R <- 6371
and check the output:
sum(f) sum(mydistance) all.equal(f, mydistance) > sum(f) [1] 647745044 > sum(mydistance) [1] 647745044 > > all.equal(f, mydistance) [1] TRUE
source share