rpermutationvector-multiplication

Multiply permutations of two vectors in R


I've got two vectors of the length 4 and want a multiplication of the permutations of the vector:

A=(a1,a2,a3,a4)
B=(b1,b2,b3,b4)

I want:

a1*b1;a1*b2;a1*b3...a4*b4

as a list with known order or data.frame with row.names=A and colnames=B


Solution

  • Use outer(A,B,'*') which will return a matrix

    x<-c(1:4)
    y<-c(10:14)
    outer(x,y,'*')
    

    returns

         [,1] [,2] [,3] [,4] [,5]
    [1,]   10   11   12   13   14
    [2,]   20   22   24   26   28
    [3,]   30   33   36   39   42
    [4,]   40   44   48   52   56
    

    and if you want the result in a list you then can do

    z<-outer(x,y,'*')
    z.list<-as.list(t(z))
    

    head(z.list) returns

    [[1]]
    [1] 10
    
    [[2]]
    [1] 11
    
    [[3]]
    [1] 12
    
    [[4]]
    [1] 13
    
    [[5]]
    [1] 14
    
    [[6]]
    [1] 20
    

    which is x1*y1, x1*y2, x1* y3, x1*y4, x2*y1 ,... (if you want x1*y1, x2*y1, ... replace t(z) by z)