簡體   English   中英

從R中的距離矩陣中找到每個索引的最短平均距離

[英]Finding shortest mean distances per index from a distance matrix in R

我正在幫助組一個三年級的空間R實驗室,任務之一是確定一個特定的站點,該站點與一組多個其他站點最接近(即,平均距離最短)。

我使用gdistance::costDistance生成了一個距離矩陣dist_m ,它看起來像這樣:

# Sample data
m <- matrix(c(2, 1, 8, 5,
              7, 6, 3, 4,
              9, 3, 2, 8,
              1, 3, 7, 4),
            nrow  = 4,
            ncol  = 4,
            byrow = TRUE)

# Sample distance matrix
dist_m <- dist(m)

dist_m打印時如下所示:

          1         2         3
2  8.717798
3  9.899495  5.477226
4  2.645751  7.810250 10.246951

期望的輸出:從這個DIST我希望能夠識別索引值( 1234具有最低的平均距離)。 在此示例中,它將是索引4 ,其平均距離為6.90 理想情況下,我也希望返回平均距離( 6.90 )。

我可以通過以下操作找到單個索引的平均距離:

# Convert distance matrix to matrix
m = as.matrix(dist_m)

# Set diagonals and upper triangle to NA
m[upper.tri(m)] = NA
m[m == 0] = NA

# Calculate mean for index
mean(c(m[4,], m[,4]), na.rm = TRUE)

但是,理想情況下,我希望有一個解決方案可以直接識別具有最小平均距離的索引,而不必手動插入索引值(實際數據集將比這個大得多)。

因為這是針對大學班級的,所以我想使任何解決方案都盡可能簡單:對於沒有R經驗的學生,for循環和Apply函數可能很難掌握。

嘗試這個:

rMeans <- rowMeans(m, na.rm = T)
names(rMeans) <- NULL
which(rMeans == min(rMeans, na.rm = T))
# [1] 4

或作為功能:

minMeanDist <- function(x) {
  m <- as.matrix(x)
  m[upper.tri(m)] <- NA
  m[m == 0] <- NA
  rMeans <- rowMeans(m, na.rm = T)
  names(rMeans) <- NULL
  mmd <- min(rMeans, na.rm = T)
  ind <- which(rMeans == mmd)
  list(index = ind, min_mean_dist = mmd)
}
minMeanDist(dist_m)
# $index
# [1] 4
# 
# $min_mean_dist
# [1] 6.900984

如果要使用tidyverse這是一種方法:

as.matrix(dist_m) %>%
    as.tibble() %>%
    rownames_to_column(var = "start_node") %>%
    gather(end_node, dist, -start_node) %>% # go long
    filter(dist != 0) %>% # drop identity diagonal
    group_by(start_node) %>% # now summarise
    summarise(mean_dist = mean(dist)) %>%
    filter(mean_dist == min(mean_dist)) # chose minimum mean_dist

# A tibble: 1 x 2
  start_node mean_dist
       <chr>     <dbl>
1          4  6.900984

它有點長,但是通過管道可以很容易地看到每一行發生了什么,並且您得到了不錯的輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM