Search code examples
rvectorcombinationsmultiplication

Product between all combinations of a vector's elements


Suppose I have a vector c(1, 2, 3, 4) with no duplicated values. I need a vector c(1 * 2, 1 * 3, 1 * 4, 2 * 3, 2 * 4, 3 * 4), so the multiplication is done in all possible combinations of this vector's values. Is there a way of doing that? Thanks in advance!


Solution

  • We can use combn with anonymous function call

    combn(vec, 2, FUN = function(x) x[1] * x[2])
    #[1]  2  3  4  6  8 12
    

    data

    vec <- 1:4