简体   繁体   English

R中的成对交互矩阵

[英]Pairwise interaction matrix in R

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). 我正在尝试计算R中的成对矩阵,该矩阵计算个体与其他个体交互的次数(因此矩阵将包括与个体数量相对应的N个行和列)。 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'))

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: 数据是相互作用的方向是无关紧要的,因此每个单元格应该计算单个X作用于Y的次数加上Y作用于X的次数。理想情况下,上面的数据框应该给出一个如下所示的矩阵:

     DOL JOJ NOR NIN
DOL    0   2   3   1
JOJ    2   0   2   0
NOR    3   2   0   2
NIN    1   0   2   0

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. 我开始编写一个循环来遍历我的数据集中的每个人,并计算他/她与actor-> partner和partner-> actor的交互。 I'm sure this would work, but is not ideal as the full dataset is quite large. 我确信这会起作用,但由于完整的数据集非常大,所以并不理想。 Is there a better way? 有没有更好的办法?


Update: Thanks for the responses! 更新:感谢您的回复! Both solutions work great! 两种解决方案都很棒! I'm posting my implementation of Josh's suggestion, which was very helpful. 我发布了Josh建议的实现,这非常有帮助。

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's table() will get you what you're after: Base R的table()将为您提供所需的内容:

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

In the field of graph theory, what you are looking for is an adjacency matrix : 在图论领域,你正在寻找的是一个邻接矩阵

library(igraph)
g <- graph.edgelist(as.matrix(nn), directed = FALSE)
get.adjacency(g)
#     DOL JOJ NOR NIN
# DOL   0   2   3   1
# JOJ   2   0   2   0
# NOR   3   2   0   2
# NIN   1   0   2   0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM