2017-05-29 22 views
1

給定一個帶有數字列的數據框,確定索引對矩陣的一種快速方法是什麼,以便相關數字數字的絕對距離等於某個固定值?R函數計算所有索引對之間相隔一定距離

實施例:

index x 
    1 5 
    2 7 
    3 8 
    4 9 
    5 9.5 

和輸出應該是

index1 index2 
    2  3 
    3  4 

如果固定距離爲1,且

index1 index2 
    1  2 

如果固定距離爲2

+1

如果固定距離是2,那麼還應該有一個'index = 2/index = 4'對嗎? –

+0

是否按您的示例排序x的值? – G5W

回答

1

一種選擇是sqldf,你基於x列的差異合併df到自身:

​​

另一種選擇是一個喜歡在這個崗位compute all pairwise differences within a vector in R但它需要多一點的工作,得到它在你想要的格式:

dist_mat <- as.matrix(dist(df[,2])) 
dist_mat2 <- dist_mat*lower.tri(dist_mat) 
res <- data.frame(index1=rep(row.names(dist_mat2),ncol(dist_mat2)), 
       index2=rep(colnames(dist_mat2),each=nrow(dist_mat2)), 
       x=c(dist_mat2)) 

res[res$x== 1, c("index1","index2")] 

注意,這可能是有問題的,如果你想要的地方不同的是0,因爲我得到lower.tri矩陣相乘值所以你沒有重複的組合(例如2/33/2)。然而,這樣做的好處是你只需要做一次。所以如果你想要的差異是2你可以改變最後一行res$x==2