你可以使用
outer
。
x = outer(lat, lon, FUN = function(x,y) {(sin(pi * x/180) * cos(pi * y /180))^2})
identical(x * 1500 + 4500, phi)
NBATrends的答案似乎比其他解决方案更快。以下是一些基准测试结果。
library(microbenchmark)
microbenchmark(within(df, {
phi <- (sin(pi * lat / 180) * cos(pi * lon / 180))^2
phi <- 1500*phi + 4500
}), 1500 * tcrossprod(sin(pi * lat / 180), cos(pi * lon / 180))^2 + 4500, outer(lat, lon, FUN = function(x,y) {(sin(pi * x/180) * cos(pi * y /180))^2}),
((as.matrix(l1)%*%t(as.matrix(l2)))^2) * 1500 + 4500)
Unit: microseconds
expr min lq mean median uq max neval
within(df, { phi <- (sin(pi * lat/180) * cos(pi * lon/180))^2 phi <- 1500 * phi + 4500 }) 255.670 262.0095 270.50948 266.6880 277.7060 385.467 100
1500 * tcrossprod(sin(pi * lat/180), cos(pi * lon/180))^2 + 4500 11.471 12.3770 22.30177 12.9805 13.5850 868.130 100
outer(lat, lon, FUN = function(x, y) { (sin(pi * x/180) * cos(pi * y/180))^2 }) 137.645 139.7590 144.39520 141.5700 145.1925 179.905 100
((as.matrix(l1) %*% t(as.matrix(l2)))^2) * 1500 + 4500 16.301 17.6595 20.20390 19.6215 20.5270 80.294 100