compute all pairwise differences within a vector in R -
compute all pairwise differences within a vector in R -
there several posts on computing pairwise differences among vectors, cannot find how compute differences within vector.
say have vector, v.
v<-c(1:4) i generate sec vector absolute value of pairwise differences within vector. similar to:
abs(1-2) = 1 abs(1-3) = 2 abs(1-4) = 3 abs(2-3) = 1 abs(2-4) = 2 abs(3-4) = 1 the output vector of 6 values, result of 6 comparisons:
output<- c(1,2,3,1,2,1) is there function in r can this?
let's play golf
abs(apply(combn(1:4,2), 2, diff)) @ben, yours killer!
> system.time(apply(combn(1:1000,2), 2, diff)) user scheme elapsed 6.65 0.00 6.67 > system.time(c(dist(1:1000))) user scheme elapsed 0.02 0.00 0.01 > system.time({ + v <- 1:1000 + z = outer(v,v,'-'); + z[lower.tri(z)]; + }) user scheme elapsed 0.03 0.00 0.03 who knew elegant (read understandable/flexible) code can slow.
r
Comments
Post a Comment