1

I have a problem I'm not sure how to approach. I have a list of items in a matrix and I want to create a matrix that instead holds every possible combination of two of those items.

So say I have matrix_1 that looks Like this:

Matrix_1 <- as.matrix(a,b,c)

[,1]
A
B
C

From that I would like to Make A Matrix that looks as follows

[,1] [,2]
A A
A B
A C
B A
B B
B C
C A
C B
C C

How do I do that?

  • Possible duplicate of https://stackoverflow.com/questions/18705153/generate-list-of-all-possible-combinations-of-elements-of-vector – Ronak Shah Jun 19 '19 at 08:36

1 Answers1

5

We can use expand.grid

as.matrix(expand.grid(LETTERS[1:3], LETTERS[1:3]))

--

Or using crossing

library(tidyverse)
crossing(A1= LETTERS[1:3], B1 = LETTERS[1:3])

Or with outer

c(t(outer(LETTERS[1:3], LETTERS[1:3], paste0)))
#[1] "AA" "AB" "AC" "BA" "BB" "BC" "CA" "CB" "CC"
akrun
  • 874,273
  • 37
  • 540
  • 662