从R中的矩阵中删除对角线元素 [英] Removing diagonal elements from matrix in R

查看:1013
本文介绍了从R中的矩阵中删除对角线元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用R从矩阵L中删除对角元素(diagL)?我尝试使用以下内容:

How can I remove the diagonal elements (diagL) from my matrix L using R? I tried using the following:

subset(L, select=-diag(L)) or
subset(L, select=-c(diag(L)))

但是我得到0个数字...

but I get 0 numbers...

推荐答案

R编程语言?我更喜欢C,更容易拼写.

The R programming language? I like C better, it is easier to spell.

一种方法是用我喜欢的数字创建一个矩阵:

One way is to create a matrix with the numbers the way I like them to look:

a<-t(matrix(1:16,nrow=4,ncol=4))

如下所示:

     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16

删除对角线上的值:

diag(a)=NA

其结果是:

     [,1] [,2] [,3] [,4]
[1,]   NA    2    3    4
[2,]    5   NA    7    8
[3,]    9   10   NA   12
[4,]   13   14   15   NA

要真正删除值,而不仅仅是删除它们,我们需要重铸:

To actually REMOVE the values, rather than just making them go away, we need to recast:

a<-t(matrix(t(a)[which(!is.na(a))],nrow=3,ncol=4))

这将导致:

     [,1] [,2] [,3]
[1,]    2    3    4
[2,]    5    7    8
[3,]    9   10   12
[4,]   13   14   15

这与我们上面的C语言相同.

which is the same thing as we got in C, above.

这有点circuit回,但我认为这是正确的答案.我希望看到比我更了解R的人提供改进的解决方案.

This is a little circuitous but it results in what I see as a correct answer. I would be interested in seeing an improved solution by somebody that knows R better than I do.

有关作业的一些解释:

a<-t(matrix(t(a)[which(!is.na(a))],nrow=3,ncol=4))

  1. !is.na(a)为我们提供了一个TRUE,FALSE值的列表,其元素已被清空.
  2. which(!is.na(a))为我们提供了每个真实元素的下标列表.
  3. t(a)会转置矩阵,因为我们需要根据#2中的下标进行拉取.
  4. t(a)[which(!is.na(a))]为我们提供了缺少对角线NA值的数字列表.
  5. matrix(t(a)[which(!is.na(a))],nrow=3,ncol=4)将列表中的#4转换为矩阵,这是我们想要的转置.
  6. a<-t(matrix(1:16,nrow=4,ncol=4))(整个过程)将#5转置为我们想要的形式,并将其分配给a变量.
  1. The !is.na(a) gives us a list of TRUE, FALSE values for which elements were nulled out.
  2. The which(!is.na(a)) gives us a list of subscripts for each of the true elements.
  3. The t(a) transposes the matrix since we need to pull based upon the subscripts in #2.
  4. t(a)[which(!is.na(a))] gives us a list of numbers that is missing the diagonal NA values.
  5. matrix(t(a)[which(!is.na(a))],nrow=3,ncol=4) converts the list from #4 into a matrix, which is the transpose of what we want.
  6. a<-t(matrix(1:16,nrow=4,ncol=4)) (the whole thing) transposes #5 into the form we want and assigns it to the a variable.

这适用于诸如a<-t(matrix(11:26,nrow=4,ncol=4))的情况.

这篇关于从R中的矩阵中删除对角线元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆