我有以下multiset X,其中我想找到所有数字之间的距离。有没有办法将它集成到FOR LOOP中,这样如果给我一个不同大小的多重集,我就不必像下面那样手动完成它?
这个例子的最终答案是[0,2,2,3,3,4,5,6,7,8,10](已排序)
X=c(0,10,8,3,6)
L=length(X)
print(L)
##for(i in seq(from=1, to=L )){}
print(abs(X[1]-X[2]), abs(X[1]-X[3]),
abs(X[1]-X[4]), abs(X[1]-X[5]),
abs(X[1]-X[6]),
abs(X[2]-X[3]), abs(X[2]-X[4]),
abs(X[2]-X[5]), abs(X[2]-X[6]),
abs(X[3]-X[4]), abs(X[3]-X[5]),
abs(X[3]-X[6]),
abs(X[4]-X[5]), abs(X[4]-X[6]),
abs(X[5]-X[6])
)
答案 0 :(得分:4)
您可能会将此向量视为列向量并应用dist
:
sort(dist(X))
# [1] 2 2 3 3 4 5 6 7 8 10