harrelfe / Hmisc

Harrell Miscellaneous
Other
205 stars 81 forks source link

Latex converter detects incorrect type for list matrices #133

Open arcresu opened 4 years ago

arcresu commented 4 years ago

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:

https://github.com/harrelfe/Hmisc/blob/6d9bd1f5bc254b0f95cc6fdfbb0e1ca4f761a06f/R/latex.s#L140-L144

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