Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 208239

Use the geosphere::distm in a more efficient way?

$
0
0

Using location data of stores, I'm trying to find 'competitors' -- which is defined as other stores within a certain distance.

I'm using geo sphere::distm and some matrix operations like below. The problem is that my matrix is pretty big (100,000 X 100,000) and it takes very long (or my memory doesn't support this type of analysis). Would there be a way to make the code below more efficient? The input file looks just like the locations_data (but bigger). The desired output is the data table competitors in which each row contains pairs of competitors. I'm new in writing efficient codes in R and wanted to ask for some help.

locations_data<-cbind(id=1:100, longitude=runif(100,min=-180, max=-120), latitude=runif(100, min=50, max=85))

#require(geosphere)
mymatrix<-distm(locations_data[,2:3])

#require(data.table)
analyze_competitors<-function(mymatrix){
    mymatrix2<-matrix(as.numeric(mymatrix<1000000), nrow(mymatrix), ncol(mymatrix)) #
    competitors<-which(mymatrix2==1,arr.ind = T)
    competitors<-data.table(competitors)
    return(competitors)
}

competitors<-analyze_competitors(mymatrix)

Viewing all articles
Browse latest Browse all 208239

Trending Articles