[英]R, Create K-nearest neighbors weights in a Matrix
我有一個2列的數據框,對應於500個地理參考觀測值的樣本的X和Y直角坐標。 我想生成一個權重矩陣W ,其中每個元素等於:
* 1 : 如果觀測值j是觀測值i的k個近鄰之一 ,並且
* 0 : 否則 。
假設我們有這個數據框:
df=as.data.frame(cbind(x=rnorm(500), y=rnorm(500)))
並假設k = 20 ,那么如何用R創建這個矩陣?
使用CRAN的FastKNN
包...假設您的距離矩陣為5 * 5
,如下所示:
library(FastKNN)
df <- as.data.frame(cbind(x = rnorm(5), y=rnorm(5)))
dist_mat <- as.matrix(dist(df, method = "euclidean", upper = TRUE, diag=TRUE))
## Let's say k = 2...
k <- 2
nrst <- lapply(1:nrow(dist_mat), function(i) k.nearest.neighbors(i, dist_mat, k = k))
## Build w
w <- matrix(nrow = dim(dist_mat), ncol=dim(dist_mat)) ## all NA right now
w[is.na(w)] <- 0 ## populate with 0
for(i in 1:length(nrst)) for(j in nrst[[i]]) w[i,j] = 1
所以我的df
看起來像這樣:
> df
x y
1 -0.2109351 -0.315256132
2 0.5172415 0.003352551
3 1.5700413 -0.737475081
4 -0.2699282 -0.198414683
5 1.3997493 -0.241382737
我的w
最終看起來像這樣:
> w
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 0 1 0
[2,] 1 0 0 1 0
[3,] 0 1 0 0 1
[4,] 1 1 0 0 0
[5,] 0 1 1 0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.