How to add cellspacing and cellpadding in HTML tables generated by xtable? - r

I would like to add spacing or padding to a html table generated by xtable.
The print.xtable() parameter html.table.attributes doesn't work for me.
Here an example chunk that can be pasted in a Rmd document.
```{r results='asis'}
library(xtable)
print(xtable(cars), type='html',
html.table.attributes = 'cellspacing="5" cellpadding="5"',
include.rownames = FALSE, include.colnames=FALSE,
comment = FALSE)
```
It's a simple standalone example and I wouldn't like to create a css file for this: more details on the purpose.

You can add CSS rules to a style sheet in the R Markdown document with the style tags.
<style>
th,td{
padding:2px 5px 2px 5px;
}
</style>

Related

Format captions in kableExtra()

Is it possible to format captions in kableExtra? I would like to center and bold a caption for a table when knitting to HTML in RMarkdown. I have tried to wrap the table in a CSS div where the text was centered, but this did not produce the intended result.
Sample table:
library(kableExtra)
kable(data.frame(a = 1:3, b = 4:6), caption = "CENTER") %>%
kable_styling(bootstrap_options = "striped")
Yields:
I would like:
If the final format is HTML:
write caption within HTML center and strong tag and set escape to FALSE.
kable(
data.frame(a = 1:3, b = 4:6),
caption = "<center><strong>CENTER</strong></center>",
escape = FALSE,
format = "html"
) %>%
kable_styling(bootstrap_options = "striped")
There is a solution through css stylesheets. The trick is to identify the correct element. Let's assume a default html document.
---
title: "test"
css: template.css
output: html_document
---
The following css script will work.
.table-wrapper caption {
color: black;
text-align: center;
font-family: Arial;
font-weight: bold;
font-size: xx-large;
}
When in doubt, you can always identify the appropriate element by opening the html document in your browser and inspecting it via ctrl+shift+c.

R markdown: how to change style with internal css?

I know how to change R markdown style with a custom css file. However, when the changes are minor, I prefer internal or even inline css, to save trouble from managing two files. I googled and haven't find a solution for this. Below is a simple example of changing style with an external css file. Is there a way to do it with internal or inline css?
The R markdown file:
---
title: "test"
output:
html_document:
css: test.css
---
## Header 1 {#header1}
But how to change style with internal css?
The test.css file:
#header1 {
color: red;
}
Markdown accepts raw HTML and passes it through unaltered, so define your "styled" elements as HTML:
<h2 style="color: red;">Header 1</h2>
Of course, some tools don't actually allow the raw HTML to be passed through (for security reasons or because the final output is not HTML), so your mileage may vary.
Depending on the Markdown implementation you are using, you may be able to define styles in the attribute list (if it supports arbitrary keys):
## Header 1 {style="color: red;"}
However, that is the least likely to work.
And remember, HTML <style> tags do not need to be in the document <head> to work. If you can use raw HTML, you can include a <style> element in the body of your document (as pointed out by #user5219763 in a comment):
---
title: "test"
output:
html_document
---
<style>
#header1 {
color: red;
}
</style>
## Header 1 {#header1}
But how to change style with internal css?
If you don't want to create an external .css file, but would like to define several styles and would rather keep your code less crowded, another possibility is to use a css chunk at the beginning of your R markdown:
---
title: "test"
output: html_document
---
```{css, echo = FALSE}
#header1 {
color: red;
}
```
## Header 1 {#header1}
In the css chunk, you can control multiple styles, as you would do in an external .css file.
Another, sort of hacky option is to specify a css file in the script, then create it in the first chunk.
e.g. the first 18 lines of your .Rmd file:
---
title: "Something Important"
output:
html_document:
css: mystyle.css
---
```{r b, echo=F}
writeLines("td, th { padding : 6px }
th { background-color : coral ;
color : white;
border : 1px solid white; }
td { color : black ;
border : 1px solid skyblue }
h1, h2, h3, h4, h5, p { font-family: consolas; ",
con = "mystyle.css")
```
In the above, I first reference the file mystyle.css in the header block of markdown. Then, I create the file using writeLines(), and save it to the file specified with con = ....
Personally, I think the best option is to just throw your code in between some <script></script> tags if it's a one-off R script.
However, if you do want to create an external file, but don't want to edit a separate file, the above method provides a workaround. It just feels odd.

Display a data frame as table in R Markdown

In knitr I want to add a (small) data frame as a table using the kable package:
---
output: html_document
---
```{r}
knitr::kable(mtcars[1:5,1:5], format="html")
```
This returns a compact table as above, while changing it to format="markdown"returns a nice table but spanning the whole page:
I have found the knitr manual but it does not cover the extra formatting options for each format. How can I change the size of a knitr table or even better, where can I get this information from?
The general approach would be to use your own custom CSS and include that in the YAML at the start of the document.
You can actually sort of do this from within your document, but I would suggest editing your CSS outside of the document and working from there.
Here's a minimal example:
---
title: "Test"
date: "24 October 2015"
output:
html_document:
css: mystyle.css
---
```{r, results='asis'}
writeLines("td, th { padding : 6px } th { background-color : brown ; color : white; border : 1px solid white; } td { color : brown ; border : 1px solid brown }", con = "mystyle.css")
dset1 <- head(ToothGrowth)
knitr::kable(dset1, format = "html")
```
This should:
Create a file named "mystyle.css" with your relevant CSS styling.
Produce something that looks something like the following.

Adding custom CSS tags to an RMarkdown html document

I have an RMarkdown document outputting to HTML of the same form as the below example. What do I add where to apply unique CSS ids or classes to each plot output?
---
title: "RMarkdown"
author: "Me"
date: "Friday, March 27, 2015"
output:
html_document:
theme: null
css: style.css
---
```{r plot1, echo=FALSE, warning=FALSE, message=FALSE}
library(ggplot2)
x <- ggplot(some_r_code)
print(x)
```
```{r plot2, echo=FALSE, warning=FALSE, message=FALSE}
y <- ggplot(some_more_r_code)
print(y)
```
I've read the info page at http://rmarkdown.rstudio.com/html_document_format.html that went a ways to answering this question but didn't get me there. I have a similar question referencing the material in that page in it's comment section, and would appreciate an answer on either.
Thanks!
You can tell knitr (which is used under the hood) with results="asis" to embed a chunk's output directly into the html. Within the chunk you can use cat to simply write a style tag including your css definitions:
```{r results="asis"}
cat("
<style>
h1 {
color: red;
}
</style>
")
```
See http://yihui.name/knitr/options/#chunk_options for details.
Declaring custom css in RMarkdown
Add css between <style> and </style> tags in the regular body of the RMarkdown (i.e. not in R code area), like so:
<style>
.pad {
padding-top: 200px;
}
</style>
# This heading will be padded {.pad}
Another option is to declare css: "style.css" in yaml and store styles in a separate file (style sheet) in the same directory
Or css can be generated and applied via R code (excellent example here)
Open the resultant HTML in a browser with a Developer Tools option and look at the generated HTML. Then apply you styling to the appropriate tags/classes. For example, put the following into style.css, knit the file and you should see a red border on the plots:
img {
background-color: red;
padding: 2px;
border: 1px solid red;
border-radius: 3px;
margin: 0 5px;
max-width: 100%;
}

show html table (via xtable) in knitr-powered document

I am trying to figure out how to use xtable when creating html pages with knitr.
My main reason to work with xtable is because I want to be able to rotate column names and/or rownames.
This is my .rmd document:
---
output: html_document
---
```{r, echo=FALSE}
library(xtable)
data(tli)
tli.table <- xtable(tli[1:10,])
align(tli.table) <- "|r|r|lp{3cm}l|r|"
tt1 <- print(tli.table, rotate.rownames=TRUE,
rotate.colnames=TRUE, type = "html")
```
```{r, echo=FALSE, results = 'asis'}
tt1
```
When I knit this document to html with knit2html, the row and column names are messed up and the html code is echoed as well. What am I doing wrong? (or is there a better way to construct nicely laid out html tables through knitr?)
Peter,
I am also frustrated with the odd behaviour of xtable when recreating tables that used to work before but not in the new R Markdow v2 using pandoc for the conversion to html.
The most I could do with your table was make it render pretty but no local column alignment or column header rotation. To do this put all the code in one r chunk with the option results='asis'.
This worked for me using RStudio 0.98.1103, R version 3.1.3 (2015-03-09), Platform: x86_64-pc-linux-gnu (64-bit), Running under: Ubuntu precise (12.04.5 LTS), knitr_1.9, rmarkdown_0.5.1, and xtable_1.7-4:
Since you mention using knit2html (not available for R 3.1.3) please try my code in your installation and see if it still works.
If so this might be a reason not to get latest versions just yet.
Using Knitr's Kable the headings appear consistent with the default alignment of right-justified for numeric columns and left-justified otherwise. Xtable's headings appear always to be centred and I can't find the option for changing this behaviour.
---
output:
html_document:
self_contained: false
theme: flatly
keep_md: true
---
<style type="text/css">
table { max-width: 200%;
border: 1px solid #ccc; }
th { background-color: #000000;
color: #ffffff;
width: 2.5cm; }
td { background-color: #dcdcdc }
</style>
```{r, echo=FALSE, results = 'asis'}
library(xtable)
data(tli)
tli.table <- xtable(tli[1:10,])
align(tli.table) <- "|r|r|lp{3cm}l|r|"
print(tli.table,
rotate.rownames=F,
rotate.colnames=F,
type="html",
include.rownames = F)
```
```{r via kable, echo=FALSE, results='markup'}
require(knitr)
kable(tli.table, format = "html",
padding = 0,
row.names=F,
caption = "Via kable")
```

Resources