Canovice
Canovice

Reputation: 10481

Using combn in R to create a matrix of all possible combinations

This is related to a homework question I am working on. I need to perform a data manipulation of a few vectors into a matrix, and the TA suggested using the combn function:

# what I'm starting with
a = c(1, 2)
b = c(NA, 4, 5)
c = c(7, 8)

# what I need to get 
my_matrix
a    b    c
1   NA    7
1   NA    8
1    4    7 
1    4    8 
1    5    7 
1    5    8 
2   NA    7 
2   NA    8 
2    4    7 
2    4    8
2    5    7
2    5    8

my_matrix is a matrix with all possibly combinations of the elements in a, b and c, with column names a, b, and c. I understand what combn() is doing, but not exactly sure how to convert it into the matrix shown above?

Thanks in advance for any help!

Upvotes: 1

Views: 5861

Answers (1)

d.b
d.b

Reputation: 32558

expand.grid, mentioned in the comments to the question, is the better and much easier way to do it. But you can use combn too

#STEP 1: Get all combinations of elements of 'a', 'b', and 'c' taken 3 at a time
temp = t(combn(c(a, b, c), 3))

# STEP 2: In the first column, only keep values present in 'a'
#Repeat STEP 2 for second column with 'b', third column with 'c'
#Use setNames to rename the column names as you want
ans = setNames(data.frame(temp[temp[,1] %in% a & temp[,2] %in% b & temp[,3] %in% c,]),
                                                                  nm = c('a','b','c'))
ans
#   a  b c
#1  1 NA 7
#2  1 NA 8
#3  1  4 7
#4  1  4 8
#5  1  5 7
#6  1  5 8
#7  2 NA 7
#8  2 NA 8
#9  2  4 7
#10 2  4 8
#11 2  5 7
#12 2  5 8

Upvotes: 2

Related Questions