融化R中的下半矩阵
如何融化下半三角形加对角矩阵?
11 NA NA NA NA
12 22 NA NA NA
13 23 33 NA NA
14 24 34 44 NA
15 25 35 45 55
A <- t(matrix (c(11, NA, NA, NA, NA, 12, 22, NA, NA, NA,
13, 23, 33, NA, NA, 14, 24, 34, 44, NA,15, 25,
35, 45, 55), ncol = 5))
> A
[,1] [,2] [,3] [,4] [,5]
[1,] 11 NA NA NA NA
[2,] 12 22 NA NA NA
[3,] 13 23 33 NA NA
[4,] 14 24 34 44 NA
[5,] 15 25 35 45 55
到 row 和 col 中的 data.frame (保留以下顺序)
col row value
1 1 11
1 2 12
1 3 13
1 4 14
1 5 15
2 2 22
2 3 23
2 4 24
2 5 25
3 3 33
3 4 34
3 5 35
4 4 44
4 5 45
5 5 55
How can I melt a lower half triangle plus diagonal matrix ?
11 NA NA NA NA
12 22 NA NA NA
13 23 33 NA NA
14 24 34 44 NA
15 25 35 45 55
A <- t(matrix (c(11, NA, NA, NA, NA, 12, 22, NA, NA, NA,
13, 23, 33, NA, NA, 14, 24, 34, 44, NA,15, 25,
35, 45, 55), ncol = 5))
> A
[,1] [,2] [,3] [,4] [,5]
[1,] 11 NA NA NA NA
[2,] 12 22 NA NA NA
[3,] 13 23 33 NA NA
[4,] 14 24 34 44 NA
[5,] 15 25 35 45 55
To data.frame in row and col (preserving the following order)
col row value
1 1 11
1 2 12
1 3 13
1 4 14
1 5 15
2 2 22
2 3 23
2 4 24
2 5 25
3 3 33
3 4 34
3 5 35
4 4 44
4 5 45
5 5 55
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您也希望索引作为列,这应该可行:
我想我会解释一下。我使用了三个“技巧”:
which
的arr.ind
参数来获取索引na.omit
函数一些额外的输入If you want the indices as columns as well, this should work:
I guess I'll explain this a bit. I'm using three "tricks":
arr.ind
argument towhich
to get the indicesna.omit
function to avoid some extra typingas.vector
returns the values in the right order.我的一艘班轮。
My one liner.
这是我的第一个解决方案:
结果是:
或者,您可以使用矩阵命令:
Here's my first solution:
Results are:
Alternatively, you can use the matrix command:
这是我的尝试:
我希望我之前就知道
cbind的 arr.ind 部分。Here is my attempt:
I wish I knew about the arr.ind part of
cbindwhich before now though.这是使用 arrayInd 的方法,它与 @joran 的方法基本相同,但在其他设置中可能有用:
Here is a method using
arrayInd
which is basically the same as @joran's but might be useful in other settings: