htmlrxtable

Formatting html table in R


I would like to improve the look of an html table that I generate in R using the package xtable:

 library(xtable)
 
 html.table = xtable(<mydataframe>)
 digits(html.table) = 2

I print the table using:

 html.tab = print(html.table, type = "html", floating = FALSE)
 cat(html.tab, file = <html link>)

I would like to be able to justify the text in the table, modify the color of the header column, change the font, ...

Is there any way I can achieve that in R?


Solution

  • The idea is to :

    1. Create a css where you format "stylize" your table using some css features
    2. Create a html table using print.xtable
    3. Create a file including a link to the css file and the created html table

    So here the code creating the "res.html" file:

    ## a dummy data.frame used as an example
    library(xtable)
    n <- data.frame(x = c(1,1,1,1,1), y = c(0,1,0,1,0))
    ## the html header  
    ## here I am using a link to mystyle.css 
    html.head <- paste("<head>" ,
                 '<link rel="stylesheet" type="text/css" href="mystyle.css"/>',
                 "</head>",sep='\n')
    ## the html body
    html.table <- paste(print(xtable(n),type='html','res.html'), 
                        collapse = "\n")
    html.body <- paste("<body>", html.table,"</body>")
    ## the html file
    write(paste(html.head,html.body,sep='\n'),"res.html")
    

    the syle sheet file(mystyle.css) can contain be something like this :

    table {
       max-width: 95%;
       border: 1px solid #ccc;
    }
    
    th {
      background-color: #000000; // background for table header 
      color: #ffffff;
    }
    
    td
    {
       text-align:right;        // justify column
       background-color: #FF0000;
    }