Generate matrix with value flags

Posted by pagid on Stack Overflow See other posts from Stack Overflow or by pagid
Published on 2012-07-10T00:16:30Z Indexed on 2012/07/10 3:16 UTC
Read the original article Hit count: 144

Filed under:

I do have a solution for the following problem but it's quite ugly and it can most likely be done in a much shorter way. Would be great to get your help.

My input looks like this:

C1     C2 
A      B     
B      D    
D      C 
A      D

and my output should look like this:

A B C D
1 1 0 0
0 1 0 1
0 0 1 1  
1 0 0 1

My current solution is:

index <- unique(unlist(input[,1:2]))
output <- matrix(0,nrows=dim(input),ncols=length(index))
for(i in 1:dim(input)) {
    output[i, input[i,]$C1] <- 1
    output[i, input[i,]$C2] <- 1
}

Of course 4-5 lines is actually fine - but even as an R beginner this doesn't feel right to use a for loop. Besides that my actual data has much more than two columns, therefore this doesn't look nice in the end. How would I do that in a smarter way?

Cheers

© Stack Overflow or respective owner

Related posts about r