Is there a method that will take c(2, 3, 5) and c(7, 11) and and give me all element-wise products as an array?:
14 22
21 33
35 55
Bonus points if it can take more than two vectors or if it can take arrays as well as vectors (like take a 4D array, a 5D array, and a 6D array, and give me a 15D array as an output).
CodePudding user response:
Given two vectors a and b, we can use outer once:
mat <- outer(a, b)
The result is a matrix, with mat[i, j] for a[i] * b[j].
For more than two vectors, say a, b and c stored in a list, we iteratively apply outer:
arr <- Reduce("outer", list(a, b, c))
The result is a high-dimensional array, with arr[i, j, k] for a[i] * b[j] * c[k].
CodePudding user response:
- We can use
t(sapply(x , \(x) x * matrix(y , ncol = 2)))
- Output
[,1] [,2]
[1,] 14 22
[2,] 21 33
[3,] 35 55
- Data
x <- c(2, 3, 5)
y <- c(7, 11)
