r - Generating and Summing Matrix -
i'm relatively new r, forgive me believe relatively simple question.
i have data in form
1 2 3 4 5 0 1 1 0 0 b 1 0 1 0 1 c 0 1 0 1 0 d 1 0 0 0 0 e 0 0 0 0 1
where a-e people , 1-5 binaries of whether or not have quality. need make matrix of a-e cell a,b = 1 if sum of quality 1-5 & b sums 2. (if share @ least 1 quality). simple 5x5 be:
b c d e 1 b 1 1 c 1 0 1 d 0 1 0 1 e 0 1 0 0 1
i need sum entire matrix. (above 9). have thousands of observations, can't hand. i'm sure there easy few lines of code, i'm not experienced enough.
thanks!
edit: i've imported data .csv file columns (1-5 above) variables, in real data have 40 variables. a-e unique id observations of people, approximately 2000. know how first convert matrix, in order execute great answers have provided. thanks!
you can use matrix multiplication here
out <- tcrossprod(m) # b c d e # 2 1 1 0 0 # b 1 3 0 1 1 # c 1 0 2 0 0 # d 0 1 0 1 0 # e 0 1 0 0 1
then set diagonal one, if required
diag(out) <- 1
as davida points out in comments tcrossprod
doing m %*% t(m)
several ways them calculate sum
l here one
sum(out[upper.tri(out, diag=true)] , na.rm=true)
Comments
Post a Comment