diag() losing dimnames

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Wed, 9 Sep 1998 18:00:13 +0200


>>>>> "Jim" == Jim Robison-Cox <jimrc@mathfs.math.montana.edu> writes:

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

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

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

It's the row one :
    > m <- matrix(1:9,3,3); dimnames(m) <- list(letters[1:3], LETTERS[1:3]); m
      A B C
    a 1 4 7
    b 2 5 8
    c 3 6 9
    > diag(m)
     a NA NA 
     1  5  9 

However, of course the bug is that  R  *does* return names(.) at
all, since as Jim rightly says, this doesn't make sense.

The patch is
to replace the  'as.matrix' by 'c' in line 5 of diag.R:

--- ../R-0.62.3/src/library/base/R/diag.R	Fri Mar  6 08:37:13 1998
+++ diag.R	Wed Sep  9 17:58:11 1998
@@ -2,7 +2,7 @@
 function(x = 1, nrow, ncol = n)
 {
 	if(is.matrix(x) && nargs() == 1)
-		return(as.matrix(x)[1 + 0:(min(dim(x)) - 1) * (dim(x)[1] + 1)])
+		return(c(x)[1 + 0:(min(dim(x)) - 1) * (dim(x)[1] + 1)])
 	if(missing(x))
 		n <- nrow
 	else if(length(x) == 1 && missing(nrow) && missing(ncol)) {



    Jim> 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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._