[英]How to sum a matrix cell value into another by row/column names?
Imagine I have an overall list of authors想象一下我有一个完整的作者列表
Authors <- c("Abel","Babel","Cain","Devil","Esau")
with it I build an overall adjacency matrix, initialized with zeroes用它我建立了一个整体邻接矩阵,用零初始化
allAuthors <- matrix(0L,nrow=length(Authors),ncol=length(Authors),dimnames=list(Authors,Authors))
now I am stumbling on a paper coAuthored by these three guys现在我偶然发现了这三个人合着的一篇论文
paperAuthors <- c("Babel","Cain","Devil")
and build another adjacency matrix of their collaboration, initialized with all 1s并构建他们协作的另一个邻接矩阵,初始化为全 1
coAuth <- matrix(1L,nrow=length(paperAuthors),ncol=length(paperAuthors),dimnames=list(paperAuthors,paperAuthors))
How do I sum the coAuth matrix cell values into the corresponding allAuthors matrix cells using the row and colum names as indices ?如何使用行和列名称作为索引将 coAuth 矩阵单元格值加到相应的 allAuthors 矩阵单元格中?
In other words I'd like to obtain the cells of the allAuthors matrix having 1s at the intersection of the paperAuthors authors while all other remain 0s.换句话说,我想在paperAuthors 作者的交点处获得allAuthors 矩阵的单元格,而所有其他矩阵的单元格都为0。
Would subsetting work for your needs or do you need to define new matrix summation operation?子集化是否适合您的需求,或者您是否需要定义新的矩阵求和运算?
allAuthors[paperAuthors, paperAuthors] <-
allAuthors[paperAuthors, paperAuthors] + 1
allAuthors
First we get the indexes in the coAuth
matrix.首先我们得到coAuth
矩阵中的索引。
ind <- which(coAuth == 1, arr.ind = TRUE)
Now we have to find the corresponding indexes in the allAuthors
matrix.现在我们必须在allAuthors
矩阵中找到相应的索引。
ind.allAuthors <- cbind(
match(rownames(coAuth), rownames(allAuthors))[ind[, 'row']],
match(colnames(coAuth), colnames(allAuthors))[ind[, 'col']])
And now we can sum the elements from both matrices:现在我们可以将两个矩阵的元素相加:
allAuthors[ind.allAuthors] <- allAuthors[ind.allAuthors] + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.