-->

Geo distance calculation using SparkR

2020-07-30 00:07发布

问题:

I have a Spark dataframe in R as follows

head(df)
Lat1    Lng1    Lat2    Lng2
23.123  24.234  25.345  26.456
...     ...     ...     ...

The DataFrame contains two points Latitude and Longitude

I would like to calculate the Geo distance between the nodes in each row and add it to a new column.

In R I am using distCosine function from geosphere library.

df$dist = distCosine(cbind(df$lng1,df$lat1),cbind(df$lng2,df$lat2))

I am wondering how I should calculate it in SparkR.

SparkR produces the following error,

Error in as.integer(length(x) > 0L) : 
cannot coerce type 'S4' to vector of type 'integer'

回答1:

You cannot use standard R function directly on Spark DataFrames. If you use a recent Spark release you can you can use dapply but it is a bit verbose and slowish:

df <- createDataFrame(data.frame(
  lat1=c(23.123), lng1=c(24.234),  lat2=c(25.345),  lng2=c(26.456)))

new_schema <- do.call(
  structType, c(schema(df)$fields(), list(structField("dist", "double", TRUE))))

attach_dist <- function(df) {
  df$dist <- geosphere::distCosine(
    cbind(df$lng1, df$lat1), cbind(df$lng2, df$lat2))
  df
}

dapply(df, attach_dist, new_schema) %>% head()
    lat1   lng1   lat2   lng2     dist
1 23.123 24.234 25.345 26.456 334733.4

In practice I would rather use the formula directly. It will be much faster, all required functions are already available and it is not very complicated:

df %>% withColumn("dist", acos(
  sin(toRadians(df$lat1)) * sin(toRadians(df$lat2)) + 
  cos(toRadians(df$lat1)) * cos(toRadians(df$lat2)) * 
  cos(toRadians(df$lng1) - toRadians(df$lng2))
) * 6378137) %>% head()
    lat1   lng1   lat2   lng2     dist
1 23.123 24.234 25.345 26.456 334733.4