Reputation: 11657
Imagine I have the following matrix:
mat <- read.table(text="
0 25 7 25 9 20 26 26 22 19 22 25
25 0 21 43 23 37 43 43 41 33 36 46
7 21 0 21 22 20 22 37 35 32 35 45
25 43 21 0 26 35 43 43 38 33 37 49
9 23 22 26 0 21 24 23 24 19 22 31
20 37 20 35 21 0 34 34 39 39 43 51
26 43 22 43 24 34 0 44 36 33 37 48
26 43 37 43 23 34 44 0 50 47 51 77
22 41 35 38 24 39 36 50 0 47 50 78
19 33 32 33 19 39 33 47 47 0 73 79
22 36 35 37 22 43 37 51 50 73 0 87
25 46 45 49 31 51 48 77 78 79 87 0
", header=F)
mat <- as.matrix(mat)
I want to compute a specific network density measure which is defined as:
where Z_ijk is the number of co-occurrences between team members i and j , and max(Z_ijk) is the maximum number of co-occurrences that team member i has with any other member of team k. N_k is the number of members on the team.
To get the maximum value in each row, I did the following:
max_values <- apply(mat, 1, max)
> max_values
1 2 3 4 5 6 7 8 9 10 11 12
26 46 45 49 31 51 48 77 78 79 87 87
I thought I could divide the matrix by max_values using sweep:
sweep(mat, 1, max_values, FUN = '/')
But it does not yield the intended output. Any thoughts?
The expected output would be: divide every value in row 1 by 26, every value in row 2 by 46, and so on.
Upvotes: 1
Views: 113
Reputation: 887108
We can do this by dividing with rowMaxs
(from matrixStats
)
library(matrixStats)
mat/rowMaxs(mat)
Upvotes: 2