[英]Obtaining the distance between two entries in a vectors R
我無法計算向量中兩個條目之間的所有距離。 假設我有一個下一種形式的向量k<-c(1,3,4,5,5,5,6,7,5,4,3,7)
那么我想計算前五個到前七個忽略連續重復的五個,然后計算接下來的五個和七個之間的距離。 我有這個想法,我將向量 k 變成另一個向量c(1,1,1,5,1,1,1,7,5,1,1,7)
但我在計算五號和七號。 所以這意味着前 5 和 7 之間的距離是 4,那么接下來的 5 到 7 之間的距離是 3。
任何見解都會有所幫助:)
一種選擇是查看每五個到下七個的相對位置,然后選擇具有最小正距離的那個。
k <- c(1,3,4,5,5,5,6,7,5,4,3,7)
# position of 5s
ind5 <- which(k == 5)
# position of 7s
ind7 <- which(k == 7)
# respective positions of 5s to all 7s
dis <- sapply(ind7, function(x){
x - ind5
})
# choose smallest positive distance
apply(dis, 1, function(x){
# exclude negative distances
tmp1 <- x[x > 0]
# return value with minimum distance
min(tmp1)
})
# [1] 4 3 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.