How can I set the column widths of individual columns in the knitr
(Rmd) output of a code chunk using the xtable
package?
MWE
```{r setup, include=FALSE}
library(xtable)
```
```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```
Lets say I want to make column_#1 - 2 inches wide and column_#2 - 3 inches wide.
I'm not married to xtable
here but don't know of any other html table out packages that could do this.
You can change the css used by xtable to format the table and change columns width. It does not allow changing individual columns though.
See http://nsaunders.wordpress.com/2012/08/27/custom-css-for-html-generated-using-rstudio/
An example below:
Add a stylesheet (here named custom.css) to the same folder as your markdown file.
table {
max-width: 95%;
border: 1px solid #ccc;
}
th {
background-color: #000000;
color: #ffffff;
width: 100px;
}
td {
background-color: #dcdcdc;
width: 100px;
}
and set the options to use this stylesheet
```{r setup, include=FALSE}
library(xtable)
options(rstudio.markdownToHTML =
function(inputFile, outputFile) {
require(markdown)
markdownToHTML(inputFile, outputFile, stylesheet='custom.css')
}
)
```
```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```
It might be possible to hack the print.xtable function to get more flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With