Home > Enterprise >  Sum of absolute differences of all possible pairs in array
Sum of absolute differences of all possible pairs in array

Time:09-28

I am trying to calculate the sum of the differences of all possible pairs of an array. 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(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)

CodePudding user response:

We can use sum dist

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

CodePudding user response:

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)
  • Related