I want to multiply and then sum the unique pairs of a vector, excluding pairs made of 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 example above:
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 (i+1)
portion of the loop will not work. Is there a way to look at the next element of the set after i
, e.g. j
, so that I could write i * c((j : length(x))
?
I understand that for
loops are usually not the most efficient approach, but I could not think of how to accomplish this via apply
etc. Examples of that would be welcome, too. Thanks for your help.