1
votes

I have a df with several columns having values 0 or 1. Something like:

a b c d e
1 0 0 0 0
0 1 0 1 0
0 1 0 1 0
1 0 1 0 1

I would like to create a 5 by 5 matrix showing total count if columns have 1 in same row. I only want to consider 1's and in case of diagonal it would automatically reflect total row in that column with 1. Output something like:

  a b c d e
a 2 0 1 0 1
b 0 2 0 2 0
c 1 0 1 0 1 
d 0 2 0 2 0
e 1 0 1 0 1

Thanks.

Sudhir

1

1 Answers

2
votes

Convert to matrix and take cross product:

m <- as.matrix(d)
crossprod(m,m)