Return a Matrix that has all possible column multiplications of another Matrix (R)

Asked

Viewed 102 times

2

Be a Matrix :

bb=replicate(3, rnorm(3))

           [,1]       [,2]       [,3]
[1,]  0.5556358  1.6611142  0.2374830
[2,] -0.6672456 -0.5038430  0.9814712
[3,] -0.1391022 -1.2072500 -0.6219965

How can I return a second matrix with all possible column multiplications ?

The resulting matrix would be :

          [,1]         [,2]         [,3]          [,4]          [,5]          [,6]          [,7]          [,8]          [,9]                  
[1,]  [1,1]*[1,1]  [1,1]*[1,2]  [1,1]*[1,3]   [1,1]*[1,2]   [1,2]*[1,2]   [1,3]*[1,2]   [1,1]*[1,3]   [1,2]*[1,3]   [1,3]*[1,3]           
[2,]  [2,1]*[2,1]  [2,1]*[2,2]  [2,1]*[2,3]   [2,1]*[2,2]   [2,2]*[2,2]   [2,3]*[2,2]   [2,1]*[2,3]   [2,2]*[2,3]   [2,3]*[2,3]   
[3,]  [3,1]*[3,1]  [3,1]*[3,2]  [3,1]*[3,3]   [3,1]*[3,2]   [3,2]*[3,2]   [3,3]*[3,2]   [3,1]*[3,3]   [3,2]*[3,3]   [3,3]*[3,3] 

1 answer

1


If I understand correctly, you want all combinations of the multiplication element to the element of the columns 1 to 3, resulting in 9 combinations (three of them redundant) i.e.: (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3).

If so, one way to do it is by creating the index combinations and then using apply to perform the multiplications:

indices <- merge(1:ncol(bb), 1:ncol(bb))
results <- apply(indices, 1, function(i) bb[,i[1]]*bb[,i[2]])

Or you can do it directly using lapply combined with sapply:

 results <- lapply(1:3, function(i) sapply(1:3, function(j){bb[,i] * bb[,j]}))
 results <- do.call("cbind", results)

The last do.call is to rebuild the matrix.

Result (same in both cases):

 results   
                [,1]        [,2]       [,3]        [,4]        [,5]       [,6]       [,7]
    [1,] 0.987438763  0.09896978 -1.4313778  0.09896978 0.009919619 -0.1434652 -1.4313778
    [2,] 0.001977491 -0.01836587 -0.0155266 -0.01836587 0.170572190  0.1442026 -0.0155266
    [3,] 0.297173072 -0.57771732  0.5811062 -0.57771732 1.123107495 -1.1296955  0.5811062
               [,8]      [,9]
    [1,] -0.1434652 2.0749057
    [2,]  0.1442026 0.1219096
    [3,] -1.1296955 1.1363222

Browser other questions tagged

You are not signed in. Login or sign up in order to post.