0

Say I have a list (a, b, c), I Want to find out all the possible combinations of them and store in a matrix like:

      a b c
 [1,] 1 0 0
 [2,] 0 1 0
 [3,] 0 0 1
 [4,] 1 1 0
 [5,] 1 0 1
 [6,] 0 1 1
 [7,] 1 1 1`

I don't know how to make it. Thanks for the help!

vincent
  • 307
  • 1
  • 2
  • 11

2 Answers2

3

To do exactly what you want, use permutations in the gtools package. This works as follows:

m <- permutations(2, 3, v=c(0,1), repeats.allowed=T)
colnames(m) <- c('a','b','c')
# delete [0,0,0]
m <- m[-1,]

Yields:

     a b c
[1,] 0 0 1
[2,] 0 1 0
[3,] 0 1 1
[4,] 1 0 0
[5,] 1 0 1
[6,] 1 1 0
[7,] 1 1 1 
Edward Carney
  • 1,372
  • 9
  • 7
1

Idea was taken from the comment section under this question: Generate all combinations of length 2 using 3 letters

My adaptation is not very elegant... but it seems to do the job.

output <- expand.grid(rep(list(c('a', 'b', 'c')), 3))
colnames(output) <- c('a', 'b', 'c')
for (col in colnames(output)) { 
  output[, col] <- as.character(output[,col])
  output[, col] <- ifelse(output[, col]==col, 1, 0)
}
output <- output[!duplicated(output), ]
rownames(output) <- NULL
print(output)
# a b c
# 1 1 0 0
# 2 0 0 0
# 3 1 1 0
# 4 0 1 0
# 5 1 0 1
# 6 0 0 1
# 7 1 1 1
# 8 0 1 1
12b345b6b78
  • 995
  • 5
  • 16