Misalignment of <NA> in rownames (PR#1905)

brahm@alum.mit.edu brahm@alum.mit.edu
Tue, 13 Aug 2002 21:56:41 +0200 (MET DST)


An NA in the rownames of a matrix (or dataframe) causes misalignment when the
matrix is printed:

R> x <- matrix(1:12, 3,4, dimnames=list(letters[1:3], LETTERS[1:4]))
R> rownames(x)[2] <- NA
R> x
     A B C  D
a    1 4 7 10
<NA>   2 5 8 11
c    3 6 9 12

The bug is in function Rstrlen, in src/main/printutils.c.  MatrixRowLabel and
MatrixColumnLabel (same file) rely on Rstrlen to count the characters in each
label, but Rstrlen doesn't understand NA's.  Here's a patch, to be applied
between lines 242 ("int len;") and 243 ("len = 0;"):

    if (s == CHAR(NA_STRING))
      return quote ? R_print.na_width : R_print.na_width_noquote;

which solves the problem:

R-patched> x
     A B C  D
a    1 4 7 10
<NA> 2 5 8 11
c    3 6 9 12

-----------------------------------------------------------------------------

An NA in the colnames has similar misalignment problems:

R> x <- matrix(1:12, 3,4, dimnames=list(letters[1:3], LETTERS[1:4]))
R> colnames(x)[2] <- NA
R> x
  A <NA> C  D
a 1  4 7 10
b 2  5 8 11
c 3  6 9 12

But this time it's because lines 72, 139, 213, 299, and 375 of
src/main/printarray.c use "strlen", which doesn't know about NA's:

  clabw = strlen(CHAR(STRING_ELT(cl, j)));

My patch is to replace "strlen" with "Rstrlen" in each case:

  clabw = Rstrlen(CHAR(STRING_ELT(cl, j)), 0);

and again this solves the problem:

R-patched> x
  A <NA> C  D
a 1    4 7 10
b 2    5 8 11
c 3    6 9 12

-----------------------------------------------------------------------------

References:

Don MacQueen reported a similar problem in the body of the matrix on 5/1/02:
  http://www.r-project.org/nocvs/mail/r-help/2002/3455.html
but this was fixed in R-1.5.1.

Derek Yi <Derek.Yi@fmr.com> first noted the rownames problem on 8/1/02 in
  http://www.r-project.org/nocvs/mail/r-help/2002/6366.html
and Brian D. Ripley <ripley@stats.ox.ac.uk> replied on 8/1/02 in
  http://www.r-project.org/nocvs/mail/r-help/2002/6367.html

-----------------------------------------------------------------------------

Version:
 platform = sparc-sun-solaris2.6
 arch = sparc
 os = solaris2.6
 system = sparc, solaris2.6
 status = 
 major = 1
 minor = 5.1
 year = 2002
 month = 06
 day = 17
 language = R

Search Path:
 .GlobalEnv, package:misc, package:io, package:arrays, package:ls1, package:g.data, package:db, package:ts, package:ctest, Autoloads, package:base

-- 
                              -- David Brahm (brahm@alum.mit.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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._