Sudhir
Sudhir

Reputation: 176

calculating sum of all against all columns with matching row count

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

Upvotes: 1

Views: 50

Answers (1)

Marat Talipov
Marat Talipov

Reputation: 13304

Convert to matrix and take cross product:

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

Upvotes: 2

Related Questions