Sum of absolute differences of all possible pairs in array

Viewed 231

I am trying to calculate the sum of the differences of all possible pairs of an array (sum of difference first/second + difference first/third, difference second/first + difference second/third, difference third/first + difference third/second). The original dataframe consists of multiple columns like the one below, still the colSum function doesn't work because of:

"Error in colSums(FC_TS1test1, dims = 1) : 'x' must be an array of at least two dimensions".

I appreciate your help!

array <- c(5, 3, 1)

The calculation behind it should be:

|(5-3)|+|(5-1)|=2+4=6
|(3-5)|+|(3-1)|=2+2=4
|(1-5)|+|(1-3)|=4+2=6
6+4+6=16
2 Answers

We need combinations without repetition.

sum(combn(a, 2, diff))
# [1] -94

Or, with some packages:

colSums(matrixStats::rowDiffs(RcppAlgos::comboGeneral(a, 2, repetition=F)))
# [1] -94

or

sum(unlist(RcppAlgos::comboGeneral(a, 2, repetition=F, FUN=diff)))
# [1] -94

Two smaller examples demonstrate what the core of the code does.

combn(b, 2)
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    3    3    3    4    4    2
# [2,]    4    2    5    2    5    5

RcppAlgos::comboGeneral(b, 2, repetition=F)
#      [,1] [,2]
# [1,]    3    4
# [2,]    3    2
# [3,]    3    5
# [4,]    4    2
# [5,]    4    5
# [6,]    2    5

Edit

For the absolute differences according to your recent edit we may define an anonymous function:

sum(combn(a, 2, function(x) abs(diff(x))))
# [1] 840

Data:

a <- c(3, 4, 2, 5, 4, 4, 1, 5, 5, 4, 1, 4, 7, 2, 1, 3, 5, 2, 4, 2, 
       7, 4, 4, 1, 4, 3, 4, 4, 2, 4, 1)

b <- c(3, 4, 2, 5)

We can use sum + dist

> sum(dist(array))
[1] 840
Related