Multiply unique pairs of values ​​in a vector and sum the result

I want to multiply and then sum the unique pairs of a vector, excluding pairs from the same element, such that for c(1:4)

:

(1*2) + (1*3) + (1*4) + (2*3) + (2*4) + (3*4) == 35

The following code works for the above example:

x <- c(1:4)
bar <- NULL
for( i in 1:length(x)) { bar <- c( bar, i * c((i+1) : length(x)))}
sum(bar[ 1 : (length(bar) - 2)])

      

However, my actual data is a vector of rational numbers, not integers, so the loop part (i+1)

won't work. Is there a way to look at the next set item after i

eg. j

so what could I write i * c((j : length(x))

?

I understand that loops for

are generally not the most efficient approach, but I couldn't think of how to do this through apply

etc. Greetings are also examples. Thanks for your help.

+3


source to share


1 answer


An alternative to looping would be to use combn

and multiply combinations using an argument FUN

. Then the sum

result is:

sum(combn(x = 1:4, m = 2, FUN = function(x) x[1] * x[2]))
# [1] 35

      



Better yet, use prod

in FUN

as suggested by @bgoldst:

sum(combn(x = 1:4, m = 2, FUN = prod))

      

+4


source







All Articles