suppose I have a vector and I want to create a cartesian product of k same vectors, How do I implement this in R.
Like, my vector is
m
[1] 1 2
and k is 3,
how do I get a result like a cartesian product of 3 m.
The cartesian product is implemented in R as outer
, or its infix version %o%
. Thus:
m %o% m %o% m
# , , 1
#
# [,1] [,2]
# [1,] 1 2
# [2,] 2 4
#
# , , 2
#
# [,1] [,2]
# [1,] 2 4
# [2,] 4 8
or in a more easily expandable form,
Reduce(outer, rep(list(m), 3))
which returns the same thing.