I am falling in love with the htmlTable()
function in the Gmisc
package. My tables are so much prettier than they were before. In my table I have one column with quite large entries and I'm having a hard time keeping it wide enough that the numbers don't wrap. I would imagine either a nowrap
argument by column or a column.width
argument would work for this, but I can't seem to find either. Is there a way to do this? Or should I just settle for "pretty darn good"?
I know I am a little late to the party, but here are a few ways you could go about. And for the record, there are so many ways to tweak these tables to get them looking exactly the way you want. So IMO the options are to 1) have various arguments for every single cell coloring option, cell height and width, row height and width, column height and width, etc; or 2) let the user figure something out.
That being said here are some possible solutions:
library(Gmisc)
## solution 1: quick, dirty
tbl <- `colnames<-`(matrix(1:9, 3, 3), c('one','two','three'))
(tmp <- htmlTable(tbl))
tbl[1,1] <- 'this is a very long cell, this is a very long cell, this is a very long cell, this is a very long cell'
(tmp <- htmlTable(tbl))
tbl[1,1] <- gsub(' ', ' ', tbl[1,1])
htmlTable(tbl)
Basically just collapsing any whitespace and using nbsp instead
The next solution actually uses some legit html tags:
## solution 2:
tbl <- `colnames<-`(matrix(1:9, 3, 3), c('one','two','three'))
tbl[1,1] <- 'this is a very long cell, this is a very long cell, this is a very long cell, this is a very long cell'
(tmp <- htmlTable(tbl))
(tmp <- gsub('<td', '<td nowrap="nowrap"; ', tmp))
The solution above replaces all of the cell styles (td) with one that includes nowrap. Replacing all of the cells may or may not be what you want which led me to the next option: regex
## solution 3: regex
tbl <- `colnames<-`(matrix(1:9, 3, 3), c('one','two','three'))
tbl[1,1] <- 'this is a very long cell, this is a very long cell, this is a very long cell, this is a very long cell'
(tmp <- htmlTable(tbl))
regmatches(tmp, gregexpr('<td.*?</td>', tmp))
# [[1]]
# [1] "<td style='text-align: left;'>this is a very long cell, this is a very long cell, this is a very long cell, this is a very long cell</td>"
# [2] "<td style='text-align: center;'>4</td>"
# [3] "<td style='text-align: center;'>7</td>"
# [4] "<td style='text-align: left;'>2</td>"
# [5] "<td style='text-align: center;'>5</td>"
# [6] "<td style='text-align: center;'>8</td>"
# [7] "<td style='border-bottom: 1px solid grey; text-align: left;'>3</td>"
# [8] "<td style='border-bottom: 1px solid grey; text-align: center;'>6</td>"
# [9] "<td style='border-bottom: 1px solid grey; text-align: center;'>9</td>"
I didn't go on because I think one of the above would suit fine, and regex is not my strong suit (neither is html or css for that matter).
I'm sure there are other options similar to this one. For instance, you could try to insert a width tag into the column tags.