[英]How do I create similarity matrices in r?
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).我有一个矩阵,行上是立法者,列上是问题,以及指示立法者如何对给定问题进行投票的值(0 - 缺席,1 - 支持,2 - 反对)。 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?
在 r 中有没有使用嵌套 for 循环的快速方法?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.