Stefan Lapointe
Stefan Lapointe

Reputation: 89

How to get a multidimentional array of all products of two vectors in R?

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).

Upvotes: 1

Views: 36

Answers (2)

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

  • 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)

Upvotes: 0

Zheyuan Li
Zheyuan Li

Reputation: 73385

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].

Upvotes: 3

Related Questions