Rapporter / pander

An R Pandoc Writer: Convert arbitrary R objects into markdown
http://rapporter.github.io/pander/
Open Software License 3.0
294 stars 66 forks source link

Strange behaviour of pander.data.table when sorted attribute is set #315

Closed UweBlock closed 5 years ago

UweBlock commented 6 years ago

Sorted attribute set to numeric variable throws error

This was asked on SO (Error when using pander on a data.table created with data.table::dcast).

dt.long <- data.table(
  time = c(1, 1, 2, 2), 
  T = c("c", "t", "c", "t"), 
  count=c(10, 15, 15, 20))
dt.wide <- dcast(dt.long, time ~ T, value.var = "count")
pander(dt.wide)

Error in data.table::setattr(x, "row.names", row.names.dt) : row names must be 'character' or 'integer', not 'double'

Workarounds are

# coerce to data frame
pander(as.data.frame(dt.wide))
# call with parameter
pander(dt.wide, keys.as.row.names = FALSE)
# remove sorted attribute (thanks to @akrun)
setattr(dt.wide, "sorted", NULL)
pander(dt.wide)

which all return

----------------
 time   c    t  
------ ---- ----
  1     10   15 

  2     15   20 
----------------

Sorted attribute set to integer variable removes column

However, if the time column is defined as integer (and not as numeric as above), pander() no longer throws an error but the time column is excluded from the result:

dt.long <- data.table(
  time = c(1L, 1L, 2L, 2L), 
  T = c("c", "t", "c", "t"), 
  count=c(10, 15, 15, 20))
dt.wide <- dcast(dt.long, time ~ T, value.var = "count")
pander(dt.wide)
---------
 c    t  
---- ----
 10   15 

 15   20 
---------

Again, one of the three workarounds is required to include the time column.

daroczig commented 5 years ago

The first issue (error) has been fixed for a while, the second issue seems to be due to setting the key to an int matching the row number, and keys.as.row.names param of pander.data.table defaults to TRUE and then pander removes the obvious rownames. So this seems to be intentional, although I agree it's confusing in some edge cases like this one. Documenting this at #271