Efficient Way to Convert Vector of Distances to Distance Object in R (ideally without creating a full distance matrix)

微笑、不失礼 提交于 2021-02-10 23:42:54

问题


I have a vector of distances which I get from some other procedure and want to convert it to a dist object in the R language .

Below I give an example how such a vector looks like: distVector is computed in the same way said other procedure computes the distance vector. Ideally, I would like to transform this vector into a distance matrix (dist object) without wasting resources.

I think I could just transform it to a matrix by copying it as upper triangular and lower triangular matrix, setting the diagonals to 0, and dealing with the fact that it is sort of upside down compared to the dist object structure (compare outputs below). Then again, first creating a full matrix and then (probably?) reducing it again to a vector in the dist object seems wasteful to me. Is there a better way?

Example code (note: I cannot change how distVector is computed):

rawData<-matrix(c(1,1,1,1.1,1,1,1,1,1.2,2,2,2,2.2,2,2,2,2.2,2.2,3,3,3,3.4,3,3),ncol=3,byrow=TRUE);

distVector<-integer(0);
for(i in 1:dim(rawData)[1]) {
  for(j in (i+1):dim(rawData)[1]) {
    a <- (rawData[i,]-rawData[j,]);
    distVector <- c(distVector, sqrt(a %*% a));
  }
}

print(distVector)
print(dist(rawData))

Output: Compare distVector to the output of the dist function, it is upside down)

> print(distVector)
 [1] 0.1000000 0.2000000 1.7320508 1.8547237 1.9697716 3.4641016 3.7094474 0.2236068 1.6763055
[10] 1.7916473 1.9209373 3.4073450 3.6455452 1.6248077 1.7549929 1.8547237 3.3526109 3.6055513
[19] 0.2000000 0.2828427 1.7320508 1.9899749 0.3464102 1.6248077 1.8547237 1.5099669 1.8000000
[28] 0.4000000

> print(dist(rawData))
          1         2         3         4         5         6         7
2 0.1000000                                                            
3 0.2000000 0.2236068                                                  
4 1.7320508 1.6763055 1.6248077                                        
5 1.8547237 1.7916473 1.7549929 0.2000000                              
6 1.9697716 1.9209373 1.8547237 0.2828427 0.3464102                    
7 3.4641016 3.4073450 3.3526109 1.7320508 1.6248077 1.5099669          
8 3.7094474 3.6455452 3.6055513 1.9899749 1.8547237 1.8000000 0.4000000

Many thanks, Thomas.

来源:https://stackoverflow.com/questions/34303055/efficient-way-to-convert-vector-of-distances-to-distance-object-in-r-ideally-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!