我想重塑/融化不对称矩阵,以便根据rowKey,当两个列单元格都不为零时,跨列求和的任何两行。我尝试了各种选择,但没有一个奏效。我正在寻找适用于大型非对称矩阵的通用解决方案。

#Dummy data
set.seed(123)

mat <- matrix(rbinom(20,100,0.01),4,5,dimnames=list(LETTERS[1:4],letters[1:5]))

mat
  a b c d e
A 0 3 1 1 0
B 2 0 1 1 0
C 1 1 3 0 0
D 2 2 1 2 3

rowKey <- c("A"="N1","B"="N1","C"="N2","D"="N2")

#Desired output

    N1 N2 N3 value
1   A  C  a     0
2   A  C  b     4
3   A  C  c     4
4   A  C  d     0
5   A  C  e     0
6   B  C  a     3
7   B  C  b     0
8   B  C  c     4
9   B  C  d     0
10  B  C  e     0
11  A  D  a     0
12  A  D  b     5
13  A  D  c     2
14  A  D  d     3
15  A  D  e     0
16  B  D  a     4
17  B  D  b     0
18  B  D  c     2
19  B  D  d     3
20  B  D  e     0

任何指针都将受到高度赞赏!

最佳答案

temp = expand.grid(c(split(names(rowKey), rowKey), list(N3 = colnames(mat))))

temp2 = sapply(1:nrow(temp), function(i)
    mat[row.names(mat) == temp$N1[i] | row.names(mat) == temp$N2[i],
        colnames(mat) == temp$N3[i]])

temp$value = colSums(temp2) * (colSums(temp2 > 0) == nrow(temp2))
temp
#   N1 N2 N3 value
#1   A  C  a     0
#2   B  C  a     3
#3   A  D  a     0
#4   B  D  a     4
#5   A  C  b     4
#6   B  C  b     0
#7   A  D  b     5
#8   B  D  b     0
#9   A  C  c     4
#10  B  C  c     4
#11  A  D  c     2
#12  B  D  c     2
#13  A  C  d     0
#14  B  C  d     0
#15  A  D  d     3
#16  B  D  d     3
#17  A  C  e     0
#18  B  C  e     0
#19  A  D  e     0
#20  B  D  e     0

关于r - 根据rowKey重塑/融化不对称矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47084324/

10-12 19:10