簡體   English   中英

在 R 中使用經緯度數據進行聚類

[英]Clustering using lat/lon data in R

我對 R 很陌生。目前我正在使用緯度和經度數據進行聚類分析,然后在谷歌地圖中繪制該值。 但是我的數據點非常有限……只有 20 點。 據我所知,我想使用 k-means 算法來做它,為了距離計算目的,我想使用哈弗距離( https://www.slideshare.net/AnbarasanS2/clusteranalysis-58192369)。我也嘗試基於密度的聚類但給了我很差的結果。所以,我想繼續使用 k-means。我的數據集和代碼如下 -

1   27.9745 79.0028
2   29.4716 77.7642
3   30.9688 76.5256
4   29.4716 77.7642
5   29.4716 77.7642
6   29.4716 77.7642
7   29.4716 77.7642
8   25.5648 83.4477
9   26.2946 79.041
10  22.5293 77.178
11  26.2946 79.041
12  30.7896 76.4973
13  26.2946 79.041
14  28.1856 72.2447
15  28.1856 72.2447
16  28.1856 72.2447
17  28.1856 72.2447
18  28.1856 72.2447
19  28.1856 72.2447
20  28.1856 72.2447

代碼是——

geodata = read.csv('test.csv')

#K-means clustering
#Compute the distance matrix using Geosphere package.
geo.dist <- function(df) {
  require(geosphere)
  d <- function(i,z) {
    dist <-rep(0,nrow(z))
    dist[i:nrow(z)] <-
      distHaversine(z[i:nrow(z),1:2],z[i,1:2])
    return(dist)
  }
  dm <- do.call(cbind,lapply(1:nrow(df), d, df))
  return(as.dist(df))
}

distance.matrix <-geo.dist(geodata[,c(2,3)])

#Determine the no.of clusters
wssplot.distancematrix <- function(data, nc = 15, seed = 1234) {
  wss <-rep(0,15)
  for (i in 2:nc) {
    set.seed(seed)
    wss[i] <- sum(kmeans(data, centers = i)$withinss)
  }
  plot(1:nc,wss,
       type = "b")
}

wssplot.distancematrix(distance.matrix)

但得到這個錯誤 -

dimnames(df) <- if (is.null(labels)) list(seq_len(size), seq_len(size)) else list(labels, : 'dimnames' [1] 的長度不等於數組范圍中的錯誤另外:警告消息:在 df[row(df) > col(df)] <- x 中:

顯示追溯

在 dimnames(df) <- if (is.null(labels)) list(seq_len(size), seq_len(size)) else list(labels, : 'dimnames' [1] 的長度不等於數組中重新運行時出現調試錯誤程度

如何創建 k-means 聚類並在谷歌地圖中繪制值。

提前致謝。

問候,尼基塔

您在代碼中有兩個錯誤。 評論如下:

geo.dist <- function(df) {
  require(geosphere)
  d <- function(i,z) {
    dist <-rep(0,nrow(z))
    dist[i:nrow(z)] <-
      distHaversine(z[i:nrow(z),1:2],z[i,1:2])
    return(dist)
  }
  dm <- do.call(cbind,lapply(1:nrow(df), d, df))
  return(as.dist(dm)) # return should be dm not df
}

distance.matrix <-geo.dist(geodata[,c(2,3)])

#Determine the no.of clusters
wssplot.distancematrix <- function(data, nc = 8, seed = 1234) {
  wss <-rep(0,nc) # nc = 15 is too high, to many cluster centers
  for (i in 2:nc) {
    set.seed(seed)
    wss[i] <- sum(kmeans(data, centers = i)$withinss)
  }
  plot(1:nc,wss,
       type = "b")
}

wssplot.distancematrix(distance.matrix)

在此處輸入圖片說明

暫無
暫無

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

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