Consider this simple example
library(dplyr)
library(ggplot2)
library(tidyr)
mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
x = c(1,2,3,5,6,7),
y = c(3,5,6,4,3,2))
mydata2 <- mydata %>% group_by(group) %>%
nest() %>%
mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point()))
pdf("P://mychart.pdf")
print(mydata2$myplot)
dev.off()
The code above will output a pdf with two pages. How can I show these two pages on my rmarkdown document?
Using
---
title: "crazy test"
output:
pdf_document
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos = 'h')
```
ttt
## this is a test!!
```{r label, out.width = "85%", fig.cap = "caption"}
knitr::include_graphics(path = "P://mychart.pdf")
```
will only show the first page of the pdf! Where is the other chart? :(
Any ideas?
Thanks!
One can use pdfpages to include multiple pages from a PDF file at once. However, these are included on separate pages. While it is possible to add page numbers, you cannot easily put these images into a figure environment. Fortunately, \includegraphics has an option to use individual pages from a PDF. Unfortunately, knitr::include_graphics
does not allow passing additional arguments to \includegraphics.
Here both possibilities:
---
title: "crazy test"
output:
pdf_document
header-includes:
- \usepackage{pdfpages}
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos = 'h')
```
```{r, include=FALSE}
library(dplyr)
library(ggplot2)
library(tidyr)
library(purrr)
mydata <- data_frame(group = c('a', 'a', 'a', 'b', 'b', 'b'),
x = c(1,2,3,5,6,7),
y = c(3,5,6,4,3,2))
mydata2 <- mydata %>% group_by(group) %>%
nest() %>%
mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point()))
pdf("mychart.pdf")
print(mydata2$myplot)
dev.off()
```
## this is a test!!
Only first page
```{r label, out.width = "85%", fig.cap = "caption"}
knitr::include_graphics(path = "mychart.pdf")
```
All pages but w/o caption and taking a full page
\includepdf[pages=-,nup=2,pagecommand={}]{mychart.pdf}
Alternative, using explicit LaTeX commands.
\begin{figure}
\includegraphics[page=1,width=0.5\linewidth]{mychart.pdf}
\includegraphics[page=2,width=0.5\linewidth]{mychart.pdf}
\caption{\label{fig:test} Test.}
\end{figure}
One could also put these into a R chunk with cat() and result = 'asis'. However, the options for setting caption etc. are still not used.
Here's the Rmd solution with staplr. Please be advised that you need to install pdftk for split_pdf to work
---
title: "crazy test"
output:
pdf_document
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos = 'h')
```
## Split pdf
```{r}
staplr::split_pdf("mychart.pdf", output_directory = ".", prefix = "mychart_")
```
## Add pdfs
```{r label, out.width = "85%", fig.cap = c("caption 1", "caption 2"), echo = FALSE}
flist <- list.files()
mychart_files <- flist[grep("mychart_", flist)]
knitr::include_graphics(mychart_files)
```
Also, include graphics doesn't work in a loop. But it accepts multiple paths, so that works out well.
knitr has a specific chunk option called out.extra that allows to pass options to the \includegraphics command. See about this option in knitr doc.
This means it can be used to page the option page. Using the example above, you could do
---
title: "crazy test"
output:
pdf_document:
keep_tex: TRUE
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos = 'h')
```
```{r, include=FALSE}
library(dplyr)
library(ggplot2)
library(tidyr)
library(purrr)
mydata <- tibble(group = c('a', 'a', 'a', 'b', 'b', 'b'),
x = c(1,2,3,5,6,7),
y = c(3,5,6,4,3,2))
mydata2 <- mydata %>% group_by(group) %>%
nest() %>%
mutate(myplot = map(data, ~ggplot(data = .x, aes(x = x, y = x)) + geom_point()))
pdf("mychart.pdf")
print(mydata2$myplot)
dev.off()
```
Only first page
```{r label, out.width = "85%", fig.cap = "caption"}
knitr::include_graphics(path = "mychart.pdf")
```
second page
```{r label2, out.width = "85%", fig.cap = "caption", out.extra="page=2"}
knitr::include_graphics(path = "mychart.pdf")
```
Related
I would like to set each value of a column in a datatable as an internal link to a different slide. Below is what I have tried but the link is not selectable.
---
title: "Example"
output: slidy_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r message=FALSE, warning=FALSE, include=FALSE}
library(DT)
library(tidyverse)
```
## Table
```{r carstab, echo = FALSE}
datatable(mtcars %>% rownames_to_column(var = "plot") %>% mutate(plot = ("[plot](#/plot)")),escape = TRUE)
```
## plot
```{r plot, echo = TRUE}
plot(mtcars)
```
mutate(plot = ("[plot](#/plot)")) does not work because the markdown code [plot](#/plot) will not be translated to HTML. Its a character.
You want something like <a href = '#(slide_number)'> This is a link </a> in your DT cells.
You could generate such links using paste0():
datatable(
mtcars %>%
mutate(
plot = 3,
plot = paste0("<a href = '#(", plot, ")'>link</a>"),
), escape = FALSE
)
The plot column in your DT now contains valid links to slide 3 (modify the first instance of plot in mutate() accordingly to link to different slides).
Lovely day to you all!
I want to insert a mschart into an Rmd which I would like to knit to docx.
I have no idea how to insert the plot. For "normal" docx this works:
ms_linechart(data = mtcars, x = "vs", y = "mpg", group = "gear") -> chart
doc <- read_docx()
doc <- body_add_chart(doc, chart = chart, style = "centered")
print(doc, target = "example.docx")
Here's my code so far which is not working:
---
date: "`r Sys.Date()`"
author: "Your Name"
title: "Untitled"
output:
officedown::rdocx_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.cap = TRUE)
library(officedown)
library(flextable)
library(officer)
library(mschart)
```
```{r}
body_add_chart(ms_linechart(data = mtcars, x = "vs", y = "mpg", group = "gear"))
```
Thanks for your help!
I e-mailed the developer and it is not possible.
A workaround, which is not ideal, but that might be helpful for some:
In a chunk:
#Create plot object
my_plot <-
data %>%
mschart::ms_scatterchart('x', 'y')
#Create a doc object using officer. Add chart.
doc <-
officer::read_docx() %>%
body_add_chart(chart = my_plot)
#Save document to a folder
print(doc, target = here::here(path_results, "my_plot.docx"))
#Pour that document into the rmarkdown
block_pour_docx(here::here(path_results, "my_plot.docx"))
Consider this simple example
---
title: "Untitled"
output:
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
options(knitr.table.format = "latex")
```
## Slide with R Output
```{r , echo = FALSE ,warning = FALSE}
library(knitr)
library(kableExtra)
library(dplyr)
cars %>%
filter(dist < 5) %>%
kable('latex', booktabs = T, escape = F, col.names = c( "$\\alpha$" , "$\\beta$" ) ) %>%
kable_styling(latex_options = c("striped", "hold_position"),
full_width = T)
```
Now this correcly generates the following output
The issue is that the renaming in col.names is manual and very tedious when my dataframe has many columns.
I would like to be able to able to say " if you see this variable dist in the dataframe, then map it to $\alpha$. Otherwise leave as is.
How can this be done?
Note, I am rendering the file using rmarkdown::render()
Thanks!!
I need to create multiple tables in RMarkdown and style it with the kableExtra package. As an example, I have the iris dataset. My first table displays the first 20 rows, my second table the next 20 rows, and my third table next 20 rows... Below is the code:
---
title: ""
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
landscape(kable_styling(kable(iris[1:20, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[21:40, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[41:60, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
```
It works well and it returns three tables, each one in a different sheet. In reality I have more than just three tables so I thought it would be a lot wiser to use a for loop and I made use of the answer given in this link R: why kable doesn't print inside a for loop?. Simple I put a line break after each print call as advised.
---
title: "untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
cat("\n")
}
```
But it does not work. I guess that is because I encapsulated the kable command with the commands from the kableExtra package.
Is there who can make it work? I mean is there a way that can save me from typing?
Your existing code was nearly there. I think the only change needed is to add results='asis' to the chunk option (I don't think the extra newline is necessary). Here's the full RMarkdown content which works for me
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```
I'm trying to fit large table of frequencies into my slide. There are many values, and even the rare ones would be nice to show.
I played with different options but none gives me a satisfactory solution. Here is Rmd so far:
---
title: "Untitled"
author: "author"
date: "date"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
df <- as.data.frame(table(rownames((USArrests))))
```
## table 1
```{r t1, echo = TRUE}
table(rownames((USArrests)))
```
## table 2
```{r t2}
library(knitr)
library(kableExtra)
kable(df, "html") %>%
kable_styling(bootstrap_options = "striped", font_size = 10)
```
Table 1 doesn't fit:
Table 2 could be squeezed but with tiny font, and lots of wasted space on the sides.
I also looked into pander, xtable and stargazer but failed to find solution from them either.
Any other alternatives?
You could spread your table across multiple columns to fit the space. In my example below, I split the frame up into 3 pairs of columns with uneven length.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library(dplyr)
library(magrittr)
library(knitr)
library(kableExtra)
```
## table 1
```{r, echo=TRUE, eval=FALSE}
USArrests %>% rownames %>% table
```
```{r, echo=FALSE}
df <- USArrests %>%
rownames %>%
table %>%
as_tibble
df %$%
tibble(
name1 = `.`[1:17],
n1 = n[1:17],
name2 = `.`[18:34],
n2 = n[18:34],
name3 = c(`.`[35:50], ""),
n3 = c(n[35:50], "")
) %>%
kable("html", align = c("l", "c"), col.names = rep(c("Name", "Frequency"), 3)) %>%
kable_styling(bootstrap_options = c("striped", "condensed"), font_size = 18)
```
N.B. I accept the transform step into multiple columns could have been done more elegantly and providing and more programmatic solution, however, I'll leave that to others to refine.