gpt4 book ai didi

根据 rowKey reshape /熔化非对称矩阵

转载 作者:行者123 更新时间:2023-12-04 14:09:04 25 4
gpt4 key购买 nike

我想 reshape /融化一个非对称矩阵,以便当两个列单元格根据 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

关于根据 rowKey reshape /熔化非对称矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47084324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com