Removing diagonal elements from matrix in R

Titi90 picture Titi90 · Sep 17, 2013 · Viewed 15.6k times · Source

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)))

but I get 0 numbers...

Answer

user2785663 picture user2785663 · Sep 18, 2013

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))

which looks like:

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

Delete the values on the diagonal:

diag(a)=NA

which results in:

     [,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))

Which results in:

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

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

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 bit of an explanation on the assignment:

a<-t(matrix(t(a)[which(!is.na(a))],nrow=3,ncol=4))
  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.

This works with cases such as a<-t(matrix(11:26,nrow=4,ncol=4)).