Tare Suriel
Tare Suriel

Reputation: 21

How to Create Each Possible Pair in a matrix

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?

Upvotes: 1

Views: 54

Answers (1)

akrun
akrun

Reputation: 887951

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"

Upvotes: 5

Related Questions