[Rd] [wishlist, patch] make row() and col() preserve dimnames (PR#13705)

goodrich at fas.harvard.edu goodrich at fas.harvard.edu
Sun May 17 23:50:12 CEST 2009


Full_Name: Ben Goodrich
Version: 2.9.0
OS: Linux (Debian unstable)
Submission from: (NULL) (128.103.220.16)


row(x), col(x), and functions that call them like lower.tri(x) and upper.tri(x)
do not retain the rownames or colnames of x in the matrix that is returned.
Example from R version 2.9.0 :

x <- matrix(1:9, nrow = 3, ncol = 3)
rownames(x) <- LETTERS[1:3]
colnames(x) <- letters[1:3]

dimnames(row(x)) # NULL
dimnames(col(x)) # NULL

Is there anyone for whom the expected behavior is to drop the dimnames of x ? It
is not consistent with other functions of matrices. By default, row(x) already
returns the row numbers of x (and similarly for col()), so how would seeing
integers in the rownames be helpful?

Without patch:
> row(x)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

With patch:
> row(x)
  a b c
A 1 1 1
B 2 2 2
C 3 3 3

Patch:
Index: src/library/base/R/matrix.R
===================================================================
--- src/library/base/R/matrix.R (revision 48553)
+++ src/library/base/R/matrix.R (working copy)
@@ -104,8 +104,9 @@
         labs <- rownames(x, do.NULL=FALSE, prefix="")
         res <- factor(.Internal(row(dim(x))), labels=labs)
         dim(res) <- dim(x)
-        res
-    } else .Internal(row(dim(x)))
+    } else res <- .Internal(row(dim(x)))
+    dimnames(res) <- dimnames(x)
+    res
 }

 col <- function(x, as.factor=FALSE)
@@ -114,8 +115,9 @@
         labs <- colnames(x, do.NULL=FALSE, prefix="")
         res <- factor(.Internal(col(dim(x))), labels=labs)
         dim(res) <- dim(x)
-        res
-    } else .Internal(col(dim(x)))
+    } else res <- .Internal(col(dim(x)))
+    dimnames(res) <- dimnames(x)
+    res
 }

 crossprod <- function(x, y=NULL) .Internal(crossprod(x,y))



More information about the R-devel mailing list