harrelfe/Hmisc

Latex converter detects incorrect type for list matrices

arcresu opened this issue · 0 comments

Within R/latex.s, format.df(x, ...) relies on detecting the type of its argument x to determine how to access its attributes. Here are the key lines from that method:

Hmisc/R/latex.s

Lines 140 to 144 in 6d9bd1f

xtype <- if(is.list(x)) 1 else if(length(dim(x))) 2 else 3
ncx <- if(xtype == 1) length(x) else if(xtype == 2) ncol(x) else 1
nams <- if(xtype == 1) names(x) else if(xtype == 2) dimnames(x)[[2]] else ''

The problem is that it's possible for a matrix to also be a list. For example:

l <- list(1,2, 3, 4, 5, 6)
m <- matrix(l, nrow = 2, dimnames = list(c("r1", "r2"), c("c1", "c2", "c3")))
is.list(m)
#> [1] TRUE
names(m)
#> NULL

For these kinds of objects, xtype is set to 1 and so the code tries to read the dimension names with names() rather than dimnames()[[2]] as it should. This came up in real usage when Hmisc::latex() was mangling a matrix I gave it that was accidentally a list, and took a while to track down.

It seems to me that it would make more sense if the line instead looked like:

  xtype <- if(length(dim(x))) 2 else if(is.list(x)) 1 else 3