[Solved] Taking values from two/multiple matrices in R?


Re-arranging your data into matrices with rownames makes this more convenient, as the row names are not a column, and therefore do not force a mode of character for the numeric data. Here are how the matrices would look. I created meaningless column names for this example, in order to show which columns are used for the products in the result.

> tab
       a   b    c    d
val1 210 201 2001 2020
val2 302 200 2919 3030
val3 839 939 8383 8383

> tab2
       e   f
val1 2.3 3.4
val2 3.4 8.3
val3 7.3 8.3

First, iterate over the intersection of the row names with sapply. This will run one iteration per row name. Here they all match, but that isn’t necessary. It also isn’t necessary that they be in the same order, but it is necessary that the row names be unique.

Then, to create each row, you can use the outer function. sapply returns the transpose of what you seem to want, so t is used to transpose it back. Column names could be applied to this result, if desired.

result <- t(sapply(intersect(rownames(tab), rownames(tab2)), 
      function(x) outer(as.matrix(tab[x, ]), as.matrix(tab2[x, ])))
    )

result
##        [,1]   [,2]    [,3]    [,4]   [,5]   [,6]    [,7]    [,8]
## val1  483.0  462.3  4602.3  4646.0  714.0  683.4  6803.4  6868.0
## val2 1026.8  680.0  9924.6 10302.0 2506.6 1660.0 24227.7 25149.0
## val3 6124.7 6854.7 61195.9 61195.9 6963.7 7793.7 69578.9 69578.9

To assign column names based on the column names of the original set, use outer again on the names, this time passing to paste. This ensures that the same order is used for the name computation as was used for the numeric computation.

colnames(result) <- outer(colnames(tab), colnames(tab2), FUN=paste, sep='*')
result
##         a*e    b*e     c*e     d*e    a*f    b*f     c*f     d*f
## val1  483.0  462.3  4602.3  4646.0  714.0  683.4  6803.4  6868.0
## val2 1026.8  680.0  9924.6 10302.0 2506.6 1660.0 24227.7 25149.0
## val3 6124.7 6854.7 61195.9 61195.9 6963.7 7793.7 69578.9 69578.9

This shows which columns in the inputs create columns in the output.

2

solved Taking values from two/multiple matrices in R?