[英]Pairwise distance two matrix R
我想在R中的矩陣之間運行距離。在此示例中,我使用曼哈頓距離,但我想應用其他公式。 我的問題是,是否有一種方法可以將函數逐行應用於R中的其他矩陣?
在此示例中,我只有兩個變量,但是我想應用10個以上的變量。
謝謝。
set.seed(123)
mat1 <- data.frame(x=sample(1:10000,3),
z=sample(1:10000,3))
mat2 <- data.frame(x=sample(1:100,3),
z=sample(1:1000,3))
dista<-matrix(0,ncol=2,nrow=2)
for (j in 1:nrow(mat1)){
for(i in 1:nrow(mat2)){
dista[i,j]<-sqrt((mat1[i,1]-mat2[j,1]) + (mat1[i,2]-mat2[j,2]))
}
}
dista
您可以使用proxy
程序包來解決這些問題。 默認情況下, proxy::dist
將矩陣或數據幀的每一行視為一個“對象”。
library(proxy)
proxy::dist(mat1, mat2, method="Manhattan")
[,1] [,2] [,3]
[1,] 4804 4832 4656
[2,] 3708 3736 3560
[3,] 17407 17435 17259
proxy::dist(mat1, mat2, method="Euclidean")
[,1] [,2] [,3]
[1,] 3397.036 3417.059 3295.962
[2,] 2761.996 2787.495 2708.075
[3,] 12308.674 12328.422 12204.286
在R控制台中鍵入vignette("overview", "proxy")
以查看其包含哪些相似性和距離,並查看proxy::pr_DB
的文檔(如果要添加可與proxy::dist
一起使用的函數) proxy::dist
。
您的代碼仍然是錯誤的,因為輸出的長度應為nrow(mat1) * nrow(mat2)
,其長度為9
,並且不能適合2x2矩陣(您先前定義)。 另外, i
應該穿過mat1
, j
應該穿過mat2
; 反之亦然。 為print()
更改dista[i,j] <-
,您將獲得:
dista<-matrix(0,ncol=2,nrow=2)
for (i in 1:nrow(mat1)){
for(j in 1:nrow(mat2)){
print(sqrt((mat1[i,1]-mat2[j,1]) + (mat1[i,2]-mat2[j,2])))
}
}
[1] 105.8159
[1] 129.5261
[1] 63.52165
[1] 103.257
[1] 127.4441
[1] 59.1608
[1] 105.8253
[1] 129.5338
[1] 63.53739
您可以使用outer
將計算限制為僅一個矢量化函數
y = outer(1:nrow(mat1),1:nrow(mat2),paste)
y
[,1] [,2] [,3]
[1,] "1 1" "1 2" "1 3"
[2,] "2 1" "2 2" "2 3"
[3,] "3 1" "3 2" "3 3"
sapply(as.vector(y), function(x){
aux = as.numeric(strsplit(x," ")[[1]])
sqrt((mat1[aux[1],1]-mat2[aux[2],1]) + (mat1[aux[1],2]-mat2[aux[2],2]))})
1 1 2 1 3 1 1 2 2 2 3 2 1 3 2 3 3 3
105.81588 129.52606 63.52165 103.25696 127.44411 59.16080 105.82533 129.53378 63.53739
在這里,我們首先創建一個包含所有i
和j
組合的y
矩陣,將其饋給sapply
,然后將其拆分以分別獲得i
和j
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.