The goal is to calculate the distance between all traffic counters along the highway and all the gas stations in Belgium. So I need the distance from every counter to every station. In the dataframe Belgium you can find the longitudinal and lateral distances of counters, in the dataframe Stations you can find those of the gas stations.
For now I used a for loop, this works fine for small dataframes but is very slow for huge ones, which is a characteristic of loops.
Stations1<-Stations[,c("lon","lat")]
names(Stations1)<-NULL
BELGIUM1<-BELGIUM[,c("lon","lat")]
names(BELGIUM1)<-NULL
distancesToStation <- data.frame(matrix(NA,nrow = nrow(Stations),ncol = nrow(BELGIUM)))
for (i in 1:nrow(BELGIUM)) {
for (j in 1:nrow(Stations)){
distancesToStation[j,i] = gmapsdistance(origin =
paste0(Stations1[j,1],"+",Stations1[j,2]),
destination =
paste0(BELGIUM1[i,1],"+",BELGIUM1[i,2]),
mode = "driving",key = "X")[[2]]/1000
}}
save(distancesToStation, file = 'DistanceMatrix.Rdata')
This code works perfect for small dataframes, is there a way to speed this up?