I'm using the bookdown package with RMarkdown to generate web-based book similar to this, likewise with the option to download a pdf-version of the book.
I've included plotly graphs in my "book" which work nicely in the html-version of the book. Being interactive, the button "build book" throws an error when including pdf output in the YAML-header.
Based on this description I've found a workaround with a regular RMarkdown File to create pdfs with plotly graphs outputs. A minimal solution (outside bookdown) looks like this:
---
title: "test"
output:
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
Sys.setenv("plotly_username" = "username")
Sys.setenv("plotly_api_key" = "API")
```
```{r cars}
library(plotly)
p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')
plotly_IMAGE(p, format = "png", out_file = "output.png")
```
![Caption for the picture.](output.png)
Is there a way to include this solution within bookdown, so that the graphs are automagically interactive in the html output and static (png) in the pdf output?
Based on this blogpost I was able to come up with a solution. Note, this only works
with the "knitr" button (see this post for a workaround)
with an internet connection (1) and Plotly Account (2)
(1) See this link to export static images locally (which I didn't get to work since I failed installing PhantomJS)
(2) Plotly has a user Quota of currently 100 plots / grids per user per day
---
title: "test"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
library(pander)
Sys.setenv("plotly_username" = "YOUR PLOTLY USERNAME")
Sys.setenv("plotly_api_key" = "API KEY")
output <- knitr::opts_knit$get("rmarkdown.pandoc.to") # html / latex / docx
```
```{r, results="asis"}
print(output)
p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')
filename <- "output.png"
if(output %in% c("latex","docx")){
plotly_IMAGE(p, format = "png", out_file = filename)
pandoc.image(filename)
} else if(output == "html"){
p
} else(print("No format defined for this output filetype"))
```
Related
I am trying to make a RMarkdown report using bookdown::html_document2 to create numbered Fig. 1, Fig. 2, ... across the whole document. Here, I am using both the R-generated and the external figures. I have found that using include_graphics() will help to generate a proper Fig. X numbers, also including in numbering the external figures.
To get the script to work, I am declaring the root.dir = rprojroot::find_rstudio_root_file('C:/myRproject')) while my external figures are located within C:/myRproject/inImg. But in this case, R cannot find my external images anymore? Why is this and how can I properly claim the paths for my R Markdown input, and for external figures? Thank you!
Example:
---
title: "My awesome title"
author: "me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
toc_depth: 3
knit: (function(input, ...) {
rmarkdown::render(
input,
output_dir = "../outReports",
output_file = file.path("../outReports", glue::glue('test_{Sys.Date()}'
)))
})
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, tidy = TRUE, tidy.opts = list(comment = FALSE), message = F, warning = F)
knitr::opts_chunk$set(fig.width=6, fig.height=3)
library(knitr)
library(png)
```
```{css, echo=FALSE}
p.caption {
font-size: 0.8em;
}
```
```{r setup-root}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))
```
```{r read-libs, eval = TRUE, echo=FALSE, include = FALSE, warning = FALSE, error = FALSE }
# rm(list=ls())
getwd()
#### Source paths and functions -----------------------------------------------
source('myPaths.R') # already this one I can't find within the directory?
# Read pictures as part of teh R chunks
library(knitr)
library(png)
# Read Input data -------------------------------------------------------------------
#getwd()
load(file = "outData/dat1.Rdata")
```
## Including Plots
You can also embed plots, for example:
```{r, out.width = "50%", fig.cap = 'Add fig from internet'}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```
```{r add-extern-plot2, fig.cap = 'my numbered caption'}
# All defaults
img1_path <- "C:/myRproject/inImg/my_extern_fig.png"
img1 <- readPNG(img1_path, native = TRUE, info = TRUE)
attr(img1, "info")
include_graphics(img1_path)
```
I am using R Markdown render to automate sales reporting and I am hit with the following error message:
Error: Invalid YAML front matter (ends with ':').
R Studio, function worked previously. I have tried most quick fixes I've seen online but nothing has worked.
Additionally, if you have any advice for importing company logos, I would love to hear it. When knitted locally, it appears, but once it is sent out, it disappears. I'm sure this is due to the local file path, so any advice for calling it in a non-local manner?
---
output: html_document
params:
---
![](/Users/bingbong284/Desktop/markdown/CopyOf Header.jpg)
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = NA)
library(dplyr)
library(tidyverse)
library(knitr)
library(kableExtra)
library(yaml)
library(rmarkdown)
```
```{r echo=FALSE, message=FALSE, warning=FALSE, paged.print=FALSE, comment = NA}
today <- Sys.Date()
```
`r format(today, format="%B %d, %Y")`
To Whom It May Concern,
Below is your sales report for fictitious name.
```{r include=FALSE}
aug_rent <- read_csv("Aug R Rent.csv")
colnames(aug_rent)[colnames(aug_rent)=="Vendor ID"] <- "Landlord"
organ_aug <- arrange(aug_rent, aug_rent$'Landlord')
vendors <- unique(organ_aug$`Landlord`)
```
```{r echo=FALSE}
render_my_report <- function(vendor) {
rmarkdown::render("Remote.Rmd",
output_format = "html_document",
output_file = paste0(vendor, "_sales_report_", Sys.Date(), ".html"),
params = list(Landlord = vendor),
output_options = list(self_contained = FALSE, lib_dir = "libs"))
}
purrr::walk(vendors, render_my_report)
```
```{r echo=FALSE, message=FALSE, warning=FALSE, comment=NA}
test_data <- filter(organ_aug, organ_aug$'Landlord' == params)
last_table <- knitr::kable(test_data, captio = "August 2019 Sales Report")
kable_styling(last_table, font_size = 14)
```
If you have any questions regarding this report, please email BingBong284#ficticiousname.com or reach out to BingBong284, BingBong284#ficticiousname.com.
Thank you,
BingBong284, Finance
Function previously generated 66 unique sales reports for 66 vendor ID's, but it is now hitting me with the error listed above.
I am having a problem with my ztable,
I want to knit my Rmarkdown file to HTML but I cannot find a way to display the table I created with ztable:
z=ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.)
I tried to set
options(ztable.table="html")
and put this at the beginning as I read somewhere else
output: html_document
header-includes: \usepackage{colortbl}
but it doesn't work when I knit to HTML. My intention was to create a sort of formatting table similar to the ones made on excel and ztable looks like the only way.
Try this minimal Rmd. The key seems to be options(ztable.type = "html") and in the chunk that generates the table, r results='asis'
If that works for you, substitute your code in the appropriate place i.e. ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.).
---
title: "ztable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ztable)
library(magrittr)
options(ztable.type = "html")
```
## R Markdown
```{r results='asis'}
matrix(1:100, nrow = 10) %>%
as.data.frame() %>%
ztable() %>%
makeHeatmap() %>%
print(caption = "table 2")
```
I've run my analyses in a source Rmd file and would like to knit a clean version from a final Rmd file using only a few of the chunks from the source. I've seen a few answers with regard to pulling all of the chunks from a source Rmd in Source code from Rmd file within another Rmd and How to source R Markdown file like `source('myfile.r')`?. I share the concern with these posts in that I don't want to port out a separate .R file, which seems to be the only way that read_chunk works.
I think I'm at the point where I can import the source Rmd, but now I'm not sure how to call specific chunks from it in the final Rmd. Here's a reproducible example:
SourceCode.Rmd
---
title: "Source Code"
output:
pdf_document:
latex_engine: xelatex
---
```{r}
# Load libraries
library(knitr) # Create tables
library(kableExtra) # Table formatting
# Create a dataframe
df <- data.frame(x = 1:10,
y = 11:20,
z = 21:30)
```
Some explanatory text
```{r table1}
# Potentially big block of stuff I don't want to have to copy/paste
# But I want it in the final document
kable(df, booktabs=TRUE,
caption="Big long title for whatever") %>%
kable_styling(latex_options=c("striped","HOLD_position")) %>%
column_spec(1, width="5cm") %>%
column_spec(2, width="2cm") %>%
column_spec(3, width="3cm")
```
[Some other text, plus a bunch of other chunks I don't need for anyone to see in the clean version.]
```{r}
save(df, file="Source.Rdata")
```
FinalDoc.Rmd
---
title: "Final Doc"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
# Load libraries and data
library(knitr) # Create tables
library(kableExtra) # Table formatting
opts_chunk$set(echo = FALSE)
load("Source.Rdata")
```
As far as I can tell, this is likely the best way to load up SourceCode.Rmd (from the first linked source above):
```{r}
options(knitr.duplicate.label = 'allow')
source_rmd2 <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)
envir <- globalenv()
source(tempR, local = envir, ...)
}
source_rmd2("SourceCode.Rmd")
```
At this point, I'm at a loss as to how to call the specific chunk table1 from SourceCode.Rmd. I've tried the following as per instructions here with no success:
```{r table1}
```
```{r}
<<table1>>
```
The first seems to do nothing, and the second throws an unexpected input in "<<" error.
I wrote a function source_rmd_chunks() that sources chunk(s) by label name. See gist.
When I use interactive charts from plotly or tables from datatables and I use rmarkdown rmarkdown:::render to html I can get interactive charts in a web browser.
When I try to send this html file as an email the interactive graphs are purely not displayed.
I'd like to be able to send a static (I mean non interactive html) so the file can be rendered in the email.
Is it possible ?
Example:
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
```{r Code Chunk}
d <- diamonds[sample(1:nrow(diamonds), size = 2000),]
plot_ly(d, x = ~carat, y = ~price, color = ~carat, size = ~carat, text = ~paste("Clarity: ", clarity))
```
```{r run code, echo=FALSE, eval=FALSE}
library(rmarkdown)
library(plotly)
rmarkdown:::render('./dyn_2_statix_html.Rmd')
```
Which would give the following html page rendered: