I have a matrix with legislators on the rows, issues on the columns, and values indicating how legislators voted on a given issue (0 - absent, 1 - for, 2 - against). I need to create a similarity matrix (whether or not two legislators voted the same way if they were both present for the vote) for each issue. Is there a quick way of doing that in r without using nested for loops?
Here is how the matrix looks like:
I1 I2 I3 I4
L1 1 1 1 2
L2 1 1 0 0
L3 2 2 2 2
L4 2 2 0 0
Here is what I would like to get for the first issue:
L1 L2 L3 L4
L1 1 0 0
L2 1 0 0
L3 0 0 1
L4 0 0 1
You may try
func <- function(a, b) {ifelse(a==b & a*b != 0, 1, 0)}
lapply(dummy, function(x) {
res <-outer(x, x, func)
diag(res) <- NA
colnames(res) = rownames(res) = c("L1", "L2", "L3", "L4")
res
})
$I1
L1 L2 L3 L4
L1 NA 1 0 0
L2 1 NA 0 0
L3 0 0 NA 1
L4 0 0 1 NA
$I2
L1 L2 L3 L4
L1 NA 1 0 0
L2 1 NA 0 0
L3 0 0 NA 1
L4 0 0 1 NA
$I3
L1 L2 L3 L4
L1 NA 0 0 0
L2 0 NA 0 0
L3 0 0 NA 0
L4 0 0 0 NA
$I4
L1 L2 L3 L4
L1 NA 0 1 0
L2 0 NA 0 0
L3 1 0 NA 0
L4 0 0 0 NA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.