# diag() losing dimnames

Jim Robison-Cox jimrc@mathfs.math.montana.edu
Wed, 9 Sep 1998 09:18:19 -0600 (MDT)

```Paul,

I see that S doesn't give any names to a diag() result:

S> x <- matrix(1:9,3,3)
S> dimnames(x) <- list(c("a", "b", "c"), c("a", "b", "c"))
S> diag(x)
[1] 1 5 9
S> names(diag(x))
NULL
S> names(x[c(1,5,9)])
NULL

Names are only well-defined if rows and cols have the same labels.  Does
it make sense to have an argument for diag to tell it where to find the
names?  I doubt it. Seems better to let the user name the result of diag()
in whatever way they need.  So it seems odd to me that diag(x) has any
names.  (It doesn't in R-0.62.2)  I haven't upgraded yet, so I have to
ask: What happens if col 1 and row 1 have different names?  Is the "a" in
Paul's example coming from the row or col name?

On Wed, 9 Sep 1998, Paul Gilbert wrote:
> Using diag() to extract the diagonal of a matrix loses all but the first dimname
> (R 0.62.3). The problem seems to be in [ ]:
> >
> > x <- matrix(1:9,3,3)
> > dimnames(x) <- list(c("a", "b", "c"), c("a", "b", "c"))
> > x
>   a b c
> a 1 4 7
> b 2 5 8
> c 3 6 9
> > diag(x)
>  a NA NA
>  1  5  9
> > x[c(1,5,9)]
>  a NA NA
>  1  5  9
> >
>
> Paul Gilbert
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>

Jim Robison-Cox                 ____________
Department of Math Sciences    |            |           phone: (406)994-5340
2-214 Wilson Hall               \   BZN, MT |           FAX:   (406)994-1789
Montana State University         |  *_______|
Bozeman, MT 59717                 \_|         e-mail: jimrc@math.montana.edu

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```