I'm using Flextable to make pretty tables in a Word doc that gets created in rmarkdown. The tables are all aligned in the center of the doc. I'd like them aligned on the left.
I know body_add_flextable has an align argument, but that function appears to be for inserting a flextable into an existing doc, and not for using within an rmarkdown file creating the doc.
I also have a reference_docx file where I can adjust styles, but tables get inserted as "normal" style, and I can't adjust the table without adjusting everything else in the doc with the "normal" style.
Here's an example rmarkdown file:
---
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r cars}
exampleDF <- data.frame("Col1" = c(1:3), "Col2" = c(4:6))
example.flex <- flextable(exampleDF)
example.flex
```
Also, I'm fairly new to using both rmarkdown and Flextable, and this is my first StackOverflow question. So all kinds of apologies if this is a stupid/poorly phrased question.
Dunno if this is a new feature, but you can do this following the online vignette, by adding ft.align = ... to the chunk options.
I think the same holds true for word documents. I am posting this with html as an answer so I can share a screenshot as a result (don't use word) and also the question was not specifically for word (in the title).
---
output: html_document
---
```{r setup, include=FALSE}
library(flextable)
```{r cars, ft.align = "left"}
exampleDF <- data.frame("Col1" = c(1:3), "Col2" = c(4:6))
example.flex <- flextable(exampleDF)
example.flex
Related
I am trying to reference a table in a word document using bookdown package.
I wanted to add the reference id in the fig.cap parameter of the code chunk, but this is somehow not seen by the interpreter and I don't get the link to the reference.
As a workaround, I added my reference ID to the caption of the table, but here the full id ({#mysecondtable2}) is written in the figure caption and this looks ugly.
Any idea on how to solve this? Maybe LUA filter to remove the ugly anchor from the table caption? I don't understand how to do this.
---
title: "Untitled"
author: "Mario"
date: '2022-11-10'
output:
bookdown::word_document2:
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
See Table \#ref(tab:myfirsttable). Or click [Table \#ref(tab:mysecondtable)](#mysecondtable2).
```{r myfirsttable, echo = FALSE}
knitr::kable(cars, caption = "First three rows of cars dataset")
```
See Table \#ref(tab:mysecondtable).
```{r mysecondtable, echo = FALSE, fig.cap='{#mysecondtable2}'}
knitr::kable(head(iris, 3),
caption='{#mysecondtable2} test')
```
EDIT:
Some strange behaviour shows, that [Table \#ref(tab:mysecondtable)](#mysecondtable) seems to work. But actually it only refers to the caption of the second table but ignores the 2 at the end...
One straight-forward solution is to wrap the table into an extra div, as one can then link to that div:
Or click [Table \#ref(tab:mysecondtable)](#mysecondtable-wrapper).
::: {#mysecondtable-wrapper}
```{r mysecondtable, echo = FALSE}
knitr::kable(head(iris, 3),
caption='test')
```
:::
A slightly less crude way is to put a span into the caption:
knitr::kable(head(iris, 3),
caption='[test]{#mysecondtable}')
The difference between the two is that the link will point at the whole table when using a div, and to the caption when using a span.
I'm attempting to add a table into an RMarkdown Powerpoint Presentation using the kableExtra package. Initially, I tried to run the code without always_use_html in my YAML and the following error appeared.
Error: Functions that produce HTML output found in document targeting pptx output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: true
Note however that the HTML output will not be visible in non-HTML formats.
Execution halted
After adding always_allow_html to my YAML, my table is still not appearing as desired in my slide .
My table should look something like this
Does anyone perhaps know how to embed a kableExtra table in Rmarkdown slides?
Here is my full code
---
title: "Untitled"
output: powerpoint_presentation
always_use_html: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Table
```{r table}
library(kableExtra)
data <- data.frame(a = c(1,2,3), b = c(4,5,6))
data %>%
kable() %>%
kable_styling()
```
Try kbl() instead of kable():
library(kableExtra)
data <- data.frame(a = c(1,2,3), b = c(4,5,6))
data %>%
kbl() %>%
kable_styling()
kable() renders to html in the viewer pane when run live, and can knit to html.
Office docs don't handle the html.
Options
include, pass a table to the default powerpoint style for your document with .rmd.
See:https://support.rstudio.com/hc/en-us/articles/360004672913-Rendering-PowerPoint-Presentations-with-the-RStudio-IDE
use officer with officemarkdown
Officer bookdown summary
-advanced styling to build a custom template can be done for reproducible
-you can save to powerpoint, then use table style editing to tweak, vs. setting the styling with style_type, style_id,style_name parameters in officedown
The preview of the tables in a rmarkdown document within R does not work anymore since the last update.
Even installing a prior version of rmarkdown and of R itself did not solve the problem.
Usually, the preview of the output is created in multiple preview windows. However, this does not work anymore. All dataframes are complied within one preview and do not look as nice as before.
What I want: A preview somehow like this where you can flip through the colums and rows:
https://bookdown.org/yihui/rmarkdown/images/paged.png
What I get:
No nice format
Or even:
No nice format2
Does anyone have a solution?
I used this code:
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
summary(cars)
iris
Thank you!
Edit: the preview magically appears if I convert the data frames to tibbles.
What you are wanting is called a paged data frame in an HTML document in RMarkdown. You would need to add the df_print: paged to your YAML header.
---
title: "iris paged Data Frame"
output:
html_document:
df_print: paged
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r chunk2}
iris
```
You can control the rows printed globally with knitr::opts_chunk$set(echo = TRUE, rows.print=25) inside your setup chunk.
I am writing a Rmarkdown document using bookdown::pdf_document2 for which I have a table that needs to do several very specific things, but I simply cannot find the solution to get all of them to work at the same time:
The table needs to float to the end of the document as it would with the latex endfloat package.
The table elements have Markdown bold and italics formatting that should appear correctly in the final PDF document
One of the columns of the table has a lot of text that I would like to wrap within the table cell.
I have tried to get these three options to work with all sorts of combinations of knitr::kable, kableExtra::column_spec and pander, but I cannot find a way to get them all going at once. Below I am pasting an example Rmarkdown document with various tests, none of which fully works.
Is there a simple way to get the table to do what I want? Even a good workaround would be acceptable...
Thanks,
David
---
title: "Test table formatting"
author: "David M. Kaplan"
date: "5/24/2020"
output: bookdown::pdf_document2
header-includes:
- \usepackage[tablesfirst]{endfloat}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
```
# Data
```{r}
df.long = data.frame(
char = c('*this is some very long text with lots of words that will cause problems with word wrap if it is not properly handled with something like kableExtra*','**b**','~~c~~'),
num = c(1,2,3))
```
# Kable with format=pandoc
```{r}
knitr::kable(df.long,caption="test1",format="pandoc")
```
**Result:** Handles formatting, but table does not float and no wordwrap.
# Kable with booktab
```{r}
knitr::kable(df.long,caption="test2",booktab=TRUE)
```
**Result:** Floats, but does not handle formatting or do wordwrap.
# kableExtra for wordwrap
```{r}
knitr::kable(df.long,caption="test3",booktab=TRUE) %>%
kableExtra::column_spec(1,width="30em")
```
**Result:** Table floats and has wordwrap, but does not handle formatting.
# Pander
```{r}
pander::panderOptions("table.alignment.default","left")
pander::pander(df.long,caption="test4")
```
**Result:** Wordwrap and formatting, but does not float.
I found a solution to this problem. It basically consists of:
In the YAML header, add a header-includes entry declaring longtable to be a float flavor using some LaTeX magic I found here.
Use pander to format the table to get wordwrap
Specifically, I have the following in the YAML header:
header-includes:
- \usepackage[tablesfirst]{endfloat}
- \DeclareDelayedFloatFlavour*{longtable}{table}
and then the table can be generated with pander:
pander::panderOptions("table.alignment.default","left")
pander::pander(df.long,caption="test pander",split.cell=50)
I would like to edit a single rmarkdown (Rmd) document with a list of "problems", each followed by its solution. Each solution may contain the results of the R console, but also some explaining (markdown and LaTeX formatted) text. Besides, I would like use knitr in 2 versions: with and without the solutions, changing the source as less as possible, and compiling.
I know that I can use a logical variable in order to conditionally evaluate R code and show plots and R output, but I don't know how to show/hide blocks of (markdown and LaTeX) formatted text, unless I put all that text into R character vectors, which seems hard for keeping things clean and readable.
I found this old question,
Conditionally display a block of text in R Markdown
where the solution was given for simple short text, which was included as an argument of the R print() function.
This other old question,
insert portions of a markdown document inside another markdown document using knitr
was for having a father document and child documents which were conditionally compiled, but I don't want to slice my document into so many pieces.
You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.
```{asis, echo=FALSE}
Some arbitrary text.
1. item
2. item
Change echo=TRUE or FALSE to display/hide this chunk.
```
But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```
If you want to include inline R expressions in the text, you will have to knit the text, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
```
There is a way to hide parts of the document (including text and chunks): to comment them out with html comment marks.
And comment marks can be generated by R in a block according to a variable that can be set at the beginning of the document.
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
And just to show a complete working example, in the example below the middle section of the document can be shown or hidden by setting the hide variable to FALSE or TRUE. That might be useful in case there are several sections to hide or show at once - for example, solutions of course problems.
---
title: "Untitled"
date: "15/10/2020"
output:
word_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
hide <- TRUE #TRUE to comment out part of the document, FALSE to show.
```
## Start
Always shown.
```{r}
hide
```
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
## To hide or not to hide
To be hidden or shown according to *hide* variable.
```{r}
"Also to be hidden according to 'hide' variable"
hist(rnorm(10))
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
<!--
Never shown.
-->
## End
Always shown.
Just a caveat: in html output the hidden parts are kept as comments and can be seen just by viewing the source. On the other hand, PDF (LaTex) and Word outputs ignore html comments and the hidden parts aren't included in the knitted documents.
Therefore, when the hidden parts are supposed to be somehow confidential (e.g. exam solutions) PDF or Word output should be used instead of html.
For those looking for a solution when knitting to pdf through LaTex, the answer from #Pere won't work for you (because LaTex doesn't understand the <!--- --> pair as indicating a comment).
Below is one possible workaround:
---
output:
pdf_document
---
\newcommand{\ignore}[1]{}
```{r echo=FALSE}
include <- TRUE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```
```{r echo=FALSE}
include <- FALSE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
NOT Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```