如何基于控制变量计算空间距离矩阵?(R)

5t7ly7z5  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(147)

我对使用自定义距离函数计算距离矩阵感兴趣。此函数应考虑空间数据和两个控制变量。此距离可以是欧几里得距离。详细信息如下:
我有一个卖家和买家的数据。这个空间数据集包含城市、坐标、购买数量和两个控制变量。我想应用一个层次聚类来确定“地理市场”。为此,我想计算一个考虑了我提到的两个控制变量的距离矩阵。
我试过这样做,但我不确定我是否正确使用对象W

# Sample data (because is private info).
set.seed(123)
n <- 100
cities <- c("City1", "City2", "City3", "City4", "City5")
seller_city <- sample(cities, n, replace = TRUE)
buyer_city <- sample(cities, n, replace = TRUE)
seller_coords <- data.frame(lon = rnorm(n, -80, 1), lat = rnorm(n, 40, 1))
buyer_coords <- data.frame(lon = rnorm(n, -80, 1), lat = rnorm(n, 40, 1))
quantity <- rpois(n, 10)
var1 <- rnorm(n, 0, 1) #First control variable.
var2 <- rnorm(n, 0, 1) #Second control variable.
df <- data.frame(seller_city, buyer_city, seller_coords, buyer_coords, quantity, var1, var2)

# Compute distance matrix
city_dist <- distm(x =df[,c("lon", "lat")] ,
                             y = df[,c("lon.1", "lat.1")])
city_dist <- (city_dist - mean(city_dist)) / sd(city_dist) #Normalising, because its units differ to the control variables.
var_dist <- as.matrix(dist(df %>% select(var1, var2)))
var_dist <- (var_dist - mean(var_dist)) / sd(var_dist) #Normalising, because its units differ to the control variables.
W <- city_dist + var_dist # sum up

# Perform hierarchical clustering
hc <- hclust(as.dist(W), 
             method = "ward.D2")

其思想是用以下公式计算城市 ij 之间的距离:

其中,x 是经度,y 是纬度,v1 是控制变量1,并且 v2 是控制变量2。

kzipqqlq

kzipqqlq1#

您可以使用use_dist包及其dist_make函数来提供自定义距离函数。
在您的示例中,可以如下所示使用它

library(usedist)

# ...

distance_function <- function (v1, v2) {
   (v1[["lon"]] - v2[["lon"]])**2
  +(v1[["lat"]] - v2[["lat"]])**2 
  +(v1[["var1"]] - v2[["var2"]])**2
  +(v1[["var1"]] - v2[["var2"]])**2;
}

# Collect the data points in one dataframe
df <- data.frame(seller_city, buyer_city, seller_coords, buyer_coords, quantity, var1, var2)

# Calculate the distance matrix
city_dist <- dist_make(df, distance_function)

# Apply hierarchical clustering
hc <- hclust(as.dist(city_dist), method = "ward.D2")

使用这种方法,你可以使用任何你想要的任意距离函数。然而,你选择的函数看起来非常类似于标准的欧几里德距离,请确保检查索引是否正确

相关问题