Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well, we can't have you resorting to for-loops, now can we :)</p> <p>There is of course the question of how to represent the sparse matrix. A simple way is to have it only contain the indices of the points that are closest (and recalculate as needed). But in the solution below, I put both distance ('d1' etc) and index ('i1' etc) in a single matrix:</p> <pre><code>sparseDist &lt;- function(m, k) { m &lt;- t(m) n &lt;- ncol(m) d &lt;- vapply( seq_len(n-1L), function(i) { d&lt;-colSums((m[, seq(i+1L, n), drop=FALSE]-m[,i])^2) o&lt;-sort.list(d, na.last=NA, method='quick')[seq_len(k)] c(sqrt(d[o]), o+i) }, numeric(2*k) ) dimnames(d) &lt;- list(c(paste('d', seq_len(k), sep=''), paste('i', seq_len(k), sep='')), colnames(m)[-n]) d } </code></pre> <p>Trying it out on 9 2d-points:</p> <pre><code>&gt; m &lt;- matrix(c(0,0, 1.1,0, 2,0, 0,1.2, 1.1,1.2, 2,1.2, 0,2, 1.1,2, 2,2), 9, byrow=TRUE, dimnames=list(letters[1:9], letters[24:25])) &gt; print(dist(m), digits=2) a b c d e f g h b 1.1 c 2.0 0.9 d 1.2 1.6 2.3 e 1.6 1.2 1.5 1.1 f 2.3 1.5 1.2 2.0 0.9 g 2.0 2.3 2.8 0.8 1.4 2.2 h 2.3 2.0 2.2 1.4 0.8 1.2 1.1 i 2.8 2.2 2.0 2.2 1.2 0.8 2.0 0.9 &gt; print(sparseDist(m, 3), digits=2) a b c d e f g h d1 1.1 0.9 1.2 0.8 0.8 0.8 1.1 0.9 d2 1.2 1.2 1.5 1.1 0.9 1.2 2.0 NA d3 1.6 1.5 2.0 1.4 1.2 2.2 NA NA i1 2.0 3.0 6.0 7.0 8.0 9.0 8.0 9.0 i2 4.0 5.0 5.0 5.0 6.0 8.0 9.0 NA i3 5.0 6.0 9.0 8.0 9.0 7.0 NA NA </code></pre> <p>And trying it on a larger problem (10k points). Still, on 100k points and more dimensions it will take a long time (like 15-30 minutes).</p> <pre><code>n&lt;-1e4; m&lt;-3; m=matrix(runif(n*m), n) system.time( d &lt;- sparseDist(m, 3) ) # 9 seconds on my machine... </code></pre> <p>P.S. Just noted that you posted an answer as I was writing this: the solution here is roughly twice as fast because it doesn't calculate the same distance twice (the distance between points 1 and 13 is the same as between points 13 and 1).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload