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.
Related
I am playing around with Quarto and really like it. One feature is to change the color of inline text with the following below syntax (the word chemical will show up in red color)
[chemical]{style="color: red"}
My question is how to change the color of the text if we assign a color to name rather than the color code or built in color code? The below will not work
var="#28A569"
[chemical]{style="color: var"}
Not sure whether Quarto offers a more straightforward approach. But one option would be to use some inline code or following the R Markdown Cookbook use a small custom function.
---
title: "Untitled"
format: html
---
[chemical]{style="color: #28A569"}
```{r, echo=FALSE}
var <- "#28A569"
```
`r sprintf('[chemical]{style="color: %s"}', var)`
```{r}
colorize <- function(x, color) {
sprintf('[%s]{style="color: %s"}', x, color)
}
```
`r colorize("chemical", var)`
An easy option would be to do this using CSS variable.
---
title: CSS variable in Inline Style
format: html
engine: knitr
---
```{css, echo=FALSE}
:root {
--color1: #28A569;
--color2: yellow;
}
```
[chemical]{style="color: var(--color1);"}
[This has colored background]{style="background-color: var(--color1);"}
[This has yellow background]{style="background-color: var(--color2);"}
When using the cleanrmd package for R Markdown, the output html page is left-aligned if I specify the theme to use, while it's centered when the them is set as NULL.
theme set as NULL
---
title: "TEST"
output:
cleanrmd::html_document_clean:
theme: NULL
---
With a theme specified
---
title: "TEST"
output:
cleanrmd::html_document_clean:
theme: new.css
---
Anyone can help me to fix this?
Specify CSS rule body { margin: 0 auto; padding: 2rem;} for the entire body of the document, which will fix the issue.
---
title: "Title"
author: "Author"
date: "Date"
output:
cleanrmd::html_document_clean:
theme: new.css
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{css, echo = FALSE}
body {
margin: 0 auto;
max-width: 750px;
padding: 2rem;
}
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that
includes both content as well as the output of any embedded R code
chunks within the document.
Rendered output looks like,
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.
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%;
}
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")
```