I am working on an R Markdown document that can be downloaded from a Shiny App as a pdf. I have structured my 1-page document with a layout that presents two columns at the beginning and then again one column until the end.
The main issue is that in one of the two columns I can't insert a table generated, for example, through the kable() function of the knitr package, because I get the following error:
Package longtable Error: longtable not in 1-column mode
Below you can find some reproducible code:
---
output: pdf_document
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = T)
library(ggplot2)
library(knitr)
```
\btwocol
#### Column one
```{r}
ggplot(mtcars,
aes(x = mpg,
y = cyl)) +
geom_point()
```
\columnbreak
#### Column two
```{r}
kable(mtcars[1:10, 1:2], format = "markdown")
```
\etwocol
Note that if you remove the kable() function the script can be compiled but the table is in the standard "R" format.
Thanks!
Very simple solution: use from the kableExtra library kbl(df, longtable=F) to produce a table that is not of the longtable format.
I found a solution by using the functionalities of the grid, gridExtra and gtable package. I created and customised the table and its caption directly inside a chunk of the R Markdown file, and with the grid.draw() function I created a graphical object of that table that can now be inserted inside a two-columns layout.
Related
This works in a usual code chunk in R markdown:
m1_aov <- anova(m1)
m1_aov$`Sum Sq`[2] %>% round(3)
Unfortunately, using the latter in inline code breaks the knitr parser down
`r m1_aov$`Sum Sq`[2] %>% round(3)`
Indeed, it also breaks Stackoverflow.
I looked at this related question but could not infer a working solution to my problem. Any hint?
Expanding the comment with a working example:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
a <- tibble::tibble(`a column` = 1:10) # using tibble to get a column name with a white space
m <- mean(a$`a column`)
```
Mean is `r m`
To me this looks like a neat trick because it avoids to include unecessary long code inside the text, and do not create the problem you are facing at the (small) cost of creating new objects.
The output:
The table prints nicely in markdown but is not present in the knitted html file. I noticed that it is classified as a list but don't know how to change it to an acceptable file type. The knitted output is not formatted as a table. I appreciate the help.
library("crosstable") #important package crosstable() function
library('dplyr')
library("flextable")
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
print(tbl1)
According to ?print.flextable
Note also that a print method is used when flextable are used within R markdown documents. See knit_print.flextable().
Therefore, if we want to print in Rmarkdown, either use knitr::knit_print or remove the print as the ?knit_print.flextable documentation shows
You should not call this method directly. This function is used by the knitr package to automatically display a flextable in an "R Markdown" document from a chunk.
---
title: "Testing"
author: "akrun"
date: "09/12/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo = FALSE}
suppressPackageStartupMessages(library("crosstable")) #important package crosstable() function
suppressPackageStartupMessages(library('dplyr'))
suppressPackageStartupMessages(library("flextable"))
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
# either use knit_print or remove the print wrapper
#knitr::knit_print(tbl1)
tbl1
```
-output
I want to create a .docx report with {officedown}, but instead of using "bookmark" reference types for cross-referencing my tables and figures as suggested in ch.4.6 and ch.4.7 of the User Documentation, I would like my references to be actual "Figure" and "Table" reference types in the resulting .docx. As discussed in this stackoverflow post, this would require {SEQ Figure \\* arabic} and {SEQ Table \\* arabic} word fields and the answers show how to implement this via officer::slip_in_seqfield() or crosstable::body_add_table_legend().
However, I think, these approaches to obtain actual "Figure" and "Table" reference types only work for the {officer} syntax and not the {officedown} syntax. To be clear, so far I understood
{officer} syntax as an R-script that makes use of a dplyr chain that starts with read_docx() %>% [example]
{officedown} syntax as an Rmd-script that makes use of block_caption() and run_autonum() within a chunk [example]
(please correct me if I am wrong)
Therefore, I would like to know whether there is a way to modify the suggested approach in {officedown} in order to obtain actual "Figure" and "Table" reference types that I can also cross-reference in the text. Below is an example using the standard suggested approach:
You can also make use of the `run_autonum()` and `block_caption()` functions
of the {officer} package. Here are the cross references to Table \#ref(tab:tabmtcars2)
and Figure \#ref(fig:figmtcars2). This approach can be used for tables and figures
and the corresponding reference type in MS Word will always be "bookmark".
```{r}
# Table
run_autonum(seq_id = "tab",
bkm = "tabmtcars2") %>%
block_caption(autonum = .,
label = "mtcars table",
style = "Table Caption")
head(mtcars)
# Figure
ggplot(head(mtcars), aes(x = mpg, y = hp)) +
geom_point() + theme_bw()
run_autonum(seq_id = "fig",
bkm = "figmtcars2") %>%
block_caption(autonum = .,
label = "mtcars figure",
style = "Image Caption")
```
This is my first time posting here, so sorry if I get formatting/etc. incorrect. But if I understand you correctly, officer::run_reference may be what you are looking for. Thomas de Marchin gives a really helpful example of this here.
The essence of this is to use block_caption with officer::run_autonum in your r code block, and then use officer::run_reference in the markdown in the place of \#ref(tab:some-tab) as follows:
```{r}
block_caption(label = 'The Caption',
style = 'Table Caption',
autonum = officer::run_autonum(seq_id = 'tab', bkm = 'some-tab'))
head(mtcars) %>% flextable()
```
This is a reference to Table `r officer::run_reference('some-tab')`
As you can read in crosstable's vignette (https://danchaltiel.github.io/crosstable/articles/crosstable-report.html),
you can use this syntax:
---
title: "mtcars"
output: bookdown::word_document2
---
```{r setup, include=FALSE}
library(crosstable)
library(flextable)
library(ggplot2)
```
Table iris is given in Table \#ref(tab:tabmtcars2).
```{r tbl, echo=FALSE, results='asis'}
cat("<caption> (\\#tab:tabmtcars2) Table Iris </caption> \n\r ")
head(mtcars) %>% flextable
```
A figure about mtcars is given in Figure \#ref(fig:tabmtcars).
```{r fig, echo=FALSE, results='asis'}
cat("<caption> (\\#fig:tabmtcars) Figure of mtcars heard </caption> \n\r ")
ggplot(head(mtcars), aes(x = mpg, y = hp)) +
geom_point() + theme_bw()
```
The numbering will be correct, but it won't create any MS Word field, so you will not be able to include these bookmarks in a figure summary, for instance.
I'm not aware of any way to include such fields using Rmarkdown, but you could use the officer syntax (described in the same link) in a plain R script.
I have an R code that generates several plots and tables from my data. I want to write a report in Rmarkdown in which i want to include just the plots and the tables without rewriting the R code. One way is to use 'read_chunk' function but it does not serve my purpose. Following is a simple example of what i need.
Suppose I have the following R script 'Example.r'
x <- 1:4
y <- sin(x)
####----Table
table <- cbind(x,y)
####----Plot
plot_1 <- plot(x,y)
Now in my R markdown file i want the following:
```{r echo=FALSE, cache=FALSE}
knitr::read_chunk('Example.r')
```
The following table shows the results:
```{r Table, echo=FALSE}
```
One can depict the result in a plot as well:
```{r Plot, echo=FALSE}
```
In the above example, i will not be able to insert either the table or the plot, since both need the input 'x' and 'y' to be defined before the table and the plot commands are run. Is there a way to implement this without hardcoding 'x' and 'y' two times?
Instead of sourcing an R script, here is my workflow which might be useful to you:
(sorry I feel it should be a comment but it gets a bit lengthy)
Keep a draft.rmd and a report.rmd side by side. the draft.rmd will be your workplace with exploratory data analysis. and the report.rmd will be your polished report
Gather results (like data.frames & ggplot objects) you want to put in the report in a list. Save the list as a result_181023.rda file. in a folder like data/
Load the saved result_181023.rda file in the report.rmd, draw your figures & print your tables and polish your report the way you like.
An example:
```{r data echo=FALSE, cache=FALSE}
# a list named result.list
# With a table result.list$df
# and a ggplot object: result.list$gg1
load("data/result_181023.rda")
```
The following table shows the results:
```{r Table, echo=FALSE}
knitr::kable(result.list$df)
```
One can depict the result in a plot as well:
```{r Plot, echo=FALSE}
result.list$gg1
```
I'm using R Markdown and am trying to generate a table and centre it in a word document. Below is the code i have taken from github as a test
Table \#ref(tab:table-single) is a simple example.
```{r table-single, tidy=FALSE}
knitr::kable(
head(mtcars, 10), booktabs = TRUE,
caption = 'A table of the first 10 rows of the mtcars data.'
)
```
When i run this piece of code the table name never resolves so i get \#ref(tab:table-single) instead of Table 2.1 as can be seen from the final document
Can someone see where in my code i have made a mistake in relation to referencing my table
I am knitting to MS Word
Thanks
If you use the bookdown package to render your markdown, you will get proper cross-referencing:
---
output: bookdown::word_document2
---
Table \#ref(tab:table-single) is a simple example.
```{r table-single, tidy=FALSE}
knitr::kable(
head(mtcars, 10), booktabs = TRUE,
caption = 'A table of the first 10 rows of the mtcars data.'
)
```