I have a Geocode dataset with three columns: Latitude, Longitude and Cluster. I calculated the average center of the clusters and store the results in two lists Center_lat and Center_lon.
Now I wanna calculate the distance from each observation(3000+) to each cluster center(30) with the Haversine formula. To get a 3000 by 30 matrix.
I tried to use a nested for loop, but I got the same distance for all clusters. Here's the code.
for (i in 1:n){
for (k in 1:c){
lat1=radians(Geocode[i,1])
lon1=radians(Geocode[i,2])
lat2=radians(Center_lat[k,2])
lon2=radians(Center_lon[k,2])
}
R <- 3958.756 # Earth mean radius [miles]
dist_mat[i,] <- acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2) * cos(lon2-lon1)) * R
}
I'm also thinking using a lapply to substitute the nested loop. But I'm not sure how to use the function... Any help is appreciated.
# Convert to radian
radians = function(theta=0){return(theta * pi / 180)}
# Calculates the geodesic distance from each property to the center of it's current cluster using the
# Spherical Law of Cosines (slc)
get_dist <- function(lat1, lon1, lat2, lon2) {
R <- 3958.756 # Earth mean radius [miles]
d <- acos(sin(radians(lat1))*sin(radians(lat2)) +
cos(radians(lat1))*cos(radians(lat2)) * cos(radians(lon2)-radians(lon1))) * R
return(d) # Distance in miles
}
dist_mat<-lapply()