Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xtable + knitr set column width html

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.

like image 791
Tyler Rinker Avatar asked Nov 12 '22 18:11

Tyler Rinker


1 Answers

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.

like image 72
Rickard Avatar answered Dec 05 '22 23:12

Rickard