R中的成对交互矩阵 [英] Pairwise interaction matrix in R
问题描述
我正在尝试计算R中的成对矩阵,该矩阵计算个人与其他个人互动的次数(因此该矩阵将包含N个与个人数量相对应的行和列).我有一个数据框,在单独的列中列出了演员"和合作伙伴".
I am trying to compute a pairwise matrix in R that counts the number of times individuals interact with other individuals (so the matrix will include N number of rows and columns corresponding to number of individuals). I have a dataframe that lists "actors" and "partners" in separate columns.
nn <- data.frame(actors=c('DOL','DOL','DOL','DOL','DOL','NOR','NOR','NOR','NIN','JOJ'),partners=c('JOJ','JOJ','NOR','NOR','NIN','NIN','DOL','JOJ','NOR','NOR'))
数据的相互作用方向无关紧要,因此每个单元格应计算单个X作用于Y的次数加上Y作用于X的次数.理想情况下,上面的数据框应给出一个矩阵看起来像这样:
The data are such that direction of the interaction is irrelevant, so each cell should count the number of times individual X acts on Y plus the number of times Y acts on X. Ideally, the data frame above should give a matrix that looks like this:
DOL JOJ NOR NIN
DOL 0 2 3 1
JOJ 2 0 2 0
NOR 3 2 0 2
NIN 1 0 2 0
我开始编写一个循环,循环遍历数据集中的每个人,并从actor-> partner和partner-> actor计数他/她的互动.我敢肯定这是可行的,但由于整个数据集非常大,因此并不理想.有更好的方法吗?
I started writing a loop to cycle through each individual in my dataset and to count his/her interactions both from actor->partner and partner->actor. I'm sure this would work, but is not ideal as the full dataset is quite large. Is there a better way?
更新: 感谢您的回复!两种解决方案都很棒!我发布了Josh的建议的实现方式,这非常有帮助.
Update: Thanks for the responses! Both solutions work great! I'm posting my implementation of Josh's suggestion, which was very helpful.
x <- with(nn, table(actors, partners))
y <- t(x)
# unique individuals
u <- unique(c(rownames(x),colnames(x)))
m <- matrix(0,ncol=length(u),nrow=length(u),dimnames=list(u,u))
i1 <- as.matrix(expand.grid(rownames(x),colnames(x)))
i2 <- as.matrix(expand.grid(rownames(y),colnames(y)))
m[i1] <- x[i1]
m[i2] <- m[i2] + y[i2]
推荐答案
Base R的table()
将为您提供服务:
Base R's table()
will get you what you're after:
x <- with(nn, table(actors, partners))
x + t(x)
# partners
# actors DOL JOJ NIN NOR
# DOL 0 2 1 3
# JOJ 2 0 0 2
# NIN 1 0 0 2
# NOR 3 2 2 0
这篇关于R中的成对交互矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!