3

I have two vectors, say:

x <- c("b", "p", "t")
y <- c("a", "e", "i")

I want to get a Matrix of their possible combinations.

df <- cbind(b=c("ba", "be", "bi"), p=c("pa", "pe", "pi"), t=c("ta", "te", "ti"))
rownames(df) <- c("a", "e", "i")

I have seen Possible combinations of a matrix in R but it doesn't do the trick here.

Also I have tried CJ(x,y) with data.table, but still I would need further steps to manipulate the data.

Is there a more simple solution to this?

camille
  • 16,432
  • 18
  • 38
  • 60

2 Answers2

3

We can use outer

out <- outer(x, y, FUN = paste0)
dimnames(out) <- list(x, y)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

We also may use expand.grid

matrix(Reduce(paste0, expand.grid(x, y)), 3)
#      [,1] [,2] [,3]
# [1,] "ba" "be" "bi"
# [2,] "pa" "pe" "pi"
# [3,] "ta" "te" "ti"
jay.sf
  • 60,139
  • 8
  • 53
  • 110