使用行名和列名比较 R 中的矩阵
我试图根据行和列名比较两个5x5矩阵。请注意,在矩阵B中,第2行和第4行的名称已交换。
a <- matrix(1:25, nrow = 5)
colnames(a) = c("col1", "col2", "col3", "col4", "col5")
rownames(a) = c("row1", "row2", "row3", "row4", "row5")
a
b <- matrix(1:25, nrow = 5)
colnames(b) = c("col1", "col2", "col3", "col4", "col5")
rownames(b) = c("row1", "row4", "row3", "row2", "row5")
b
c <- b-a
c
col1 col2 col3 col4 col5
row1 0 0 0 0 0
row4 0 0 0 0 0
row3 0 0 0 0 0
row2 0 0 0 0 0
row5 0 0 0 0 0
计算差异C = B- a时,代码返回零的矩阵,就好像它在寻找矩阵中元素的位置,而不是行和列索引。我希望第4行的结果是:
d <- a["row4",] - b["row4",]
col1 col2 col3 col4 col5
2 2 2 2 2
有什么想法如何做到这一点?
I am trying to compare two 5x5 matrices based on row and column names. Note that in matrix b the names for row 2 and row 4 have been swapped.
a <- matrix(1:25, nrow = 5)
colnames(a) = c("col1", "col2", "col3", "col4", "col5")
rownames(a) = c("row1", "row2", "row3", "row4", "row5")
a
b <- matrix(1:25, nrow = 5)
colnames(b) = c("col1", "col2", "col3", "col4", "col5")
rownames(b) = c("row1", "row4", "row3", "row2", "row5")
b
c <- b-a
c
col1 col2 col3 col4 col5
row1 0 0 0 0 0
row4 0 0 0 0 0
row3 0 0 0 0 0
row2 0 0 0 0 0
row5 0 0 0 0 0
When calculating the difference c = b - a, the code returns a matrix of zeros as if it was looking for the position of the elements in the matrix rather that the row and column index. I'd expect the result for row 4 to be:
d <- a["row4",] - b["row4",]
col1 col2 col3 col4 col5
2 2 2 2 2
Any idea how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下示例将使用公共行和列从
a
中减去b
。The following example will subtract
b
froma
, using the common rows and columns.如果列名的顺序也不同,则可以在逗号后添加
sort(colnames(b))
。顺便说一句,我建议不要使用
c
作为r
中对象的名称,因为c
是创建向量的内置功能。If the column names are in different order as well, you could add a
sort(colnames(b))
after the comma.BTW, I advice not to use
c
as a name for an object inR
, sincec
is a built-in function to create a vector.