user3294195 - 2 months ago 14

R Question

I have an

`m`

`n`

`1 2 3`

4 5 6

What is the fastest way to get all possible combinations by row? In this case, that would be

`c(1,4), c(1,5), c(1,6), c(2,4), c(2,5) ... c(3,5), c(3,6)`

How do I solve this using a vectorized approach? In general an

`m`

`n`

`n^m`

Answer

You can use the `expand.grid`

function to get all combinations of the elements in each row, building a list of rows using `split`

as shown here and passing each element of that list to `expand.grid`

with the `do.call`

function:

```
(m <- rbind(1:3, 4:6))
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
do.call(expand.grid, split(m, rep(1:nrow(m), ncol(m))))
# 1 2
# 1 1 4
# 2 2 4
# 3 3 4
# 4 1 5
# 5 2 5
# 6 3 5
# 7 1 6
# 8 2 6
# 9 3 6
```

Here's an example with a 3 x 2 matrix instead of a 2 x 3 matrix:

```
(m <- matrix(1:6, nrow=3))
# [,1] [,2]
# [1,] 1 4
# [2,] 2 5
# [3,] 3 6
do.call(expand.grid, split(m, rep(1:nrow(m), ncol(m))))
# 1 2 3
# 1 1 2 3
# 2 4 2 3
# 3 1 5 3
# 4 4 5 3
# 5 1 2 6
# 6 4 2 6
# 7 1 5 6
# 8 4 5 6
```