GoogleVis chart not rendering in Rmarkdown - r

Outside of Rmarkdown the stand alone googleVis chart works fine, but when I plug it in the Rmarkdown file I am receiving just the Rmarkdown Code:
Viewer Output:
> TEST H 4/13/2016 require(googleVis) Loading required package:
> googleVis Welcome to googleVis version 0.5.10 Please read the Google
> API Terms of Use before you start using the package:
> https://developers.google.com/terms/
>
> Note, the plot method of googleVis will by default use the standard
> browser to display its output. See the googleVis package vignettes
> for more details, or visit http://github.com/mages/googleVis. To
> suppress this message use:
> suppressPackageStartupMessages(library(googleVis))
>
> dttm = data.frame(DT_ENTRY=Sys.Date()-1:20,variable="x",value=1:20)
> g1=gvisAnnotationChart(dttm,datevar="DT_ENTRY",numvar="value",idvar="variable")
> plot(g1) starting httpd help server ... done
Rmarkdown Code Below:
---
title: "test"
author: "H"
date: "4/13/2016"
output: html_document
highlight: tango
number_sections: yes
---
```{r}
require(googleVis)
dttm = data.frame(DT_ENTRY=Sys.Date()-1:20,variable="x",value=1:20)
g1=gvisAnnotationChart(dttm,datevar="DT_ENTRY",numvar="value",idvar="variable")
plot(g1)
```

The r chunk has to be declared as:
```{r plotg0, results='asis', tidy=FALSE, echo=FALSE}
The "asis" is important because it returns raw HTML

I am not sure if you still need an answer. However, I faced the same problem while trying to embed a sankey plot from gvisSankey onto a section on Rmarkdown. Thankfully, I found the solution on github.com/mages/googleVis (weirdly not recommended on Google Search).
Below is a reproducible example.
First, to create a sankey plot, I do this:
# install.packages("googleVis")
library(googleVis)
# Create a data.frame that is gvisSankey-conform
# i.e., has these columns: FROM - TO - WEIGHT
df <- data.frame(FROM = rep(c("A","B","C"), each = 3),
TO = rep(c("D","E","F"), times = 3),
WEIGHT = sample(1:10, 9, replace = TRUE))
sankeyplot <- gvisSankey(data = df,
from = "FROM",
to = "TO",
weight = "WEIGHT")
plot(sankeyplot)
plot(sankeyplot) will open a new tab containing the sankeyplot. Now, how do I embed the sankeyplot onto my Rmarkdown?
There are two important points:
To set self_contained:false in the YAML header
To set results='asis' in the R code chunk where the sankeyplot is embedded
---
title: "SankeyPlot_Example"
output:
html_document:
self_contained: false
date: '2022-10-21'
---
## Embed googleVis object (sankey plot) onto Rmarkdown
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(googleVis)
# Create a reproducible data.frame
df <- data.frame(FROM = rep(c("A","B","C"), each = 3),
TO = rep(c("D","E","F"), times = 3),
WEIGHT = sample(1:10, 9, replace = TRUE))
```
```{r results='asis'}
sankeyplot <- gvisSankey(data = df,
from = "FROM",
to = "TO",
weight = "WEIGHT")
print(sankeyplot, 'chart')
```

Related

rmarkdown powerpoint: two kable on one slide

In this example each kable is produced on one slide, even though the slide is large enough for 2.
---
title: "Untitled"
author: ""
date: "2/2/2022"
output: powerpoint_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, fig.height=5, fig.width=10)
```
## Slide with R Output
```{r}
knitr::kable(head(summary(cars),2))
```
```{r}
knitr::kable(head(summary(cars),2))
```
gives the output:
How do I make both kable on one slide one after the other.
You can use the gridExtra package https://cran.r-project.org/web/packages/gridExtra/vignettes/tableGrob.html
The documentation provides additional details about controlling formatting. I provided one example for illustration.
library(tidyverse)
library(gridExtra)
t1 <-
head(summary(cars),2) %>%
tableGrob(theme = ttheme_minimal(), rows = NULL)
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1],
col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)))
t2 <-
head(summary(cars),2) %>%
tableGrob(theme = tt3, rows = NULL)
grid.arrange(t1 , t2)

Rendering multiple Rmarkdown reports with parameters fails with "Error: `:=` can only be used within a quasiquoted argument" when data.table is used

Good morning everybody,
as stated above, I’m trying to render multiple Rmarkdown reports with different parameters for each report. Basically I have a folder of .csv files, which I have to clean up. I have packed all the steps in an .Rmd file, because this way the data gets cleaned and a short report is generated documenting the results. Some figures, some stats, nothing very dramatic, just an overview of how the cleaning went.
As each .csv file is slightly different, I have to tweak some parameters. This is the easy part. I have found some nice code in the “R for Data Science” book, which you can find here. https://r4ds.had.co.nz/r-markdown.html#parameters
This is my version:
library(dplyr)
library(stringr)
library(purrr)
# Create a vector with names
files <- c("dataframe", "datatable")
# Create a tibble with filenames and lists of parameters
reports <- tibble(
filename = str_c(files, ".html"),
params = map(files, ~ list(name = .,
factor = if_else(. == "dataframe", 2.5, 5))))
#-------------------------------------------------------------------
# make reports
reports <- reports %>%
select(output_file = filename, params) %>%
purrr::pwalk(rmarkdown::render, input = "template_datatable.Rmd")
Everything runs fine, when the .Rmd file uses data.frames.
As my .csv are about 1 GB each, I would use data.table to speed things up. But as soon as my .Rmd file contains some data.table code I get this error message:
Error: `:=` can only be used within a quasiquoted argument
If I just render one file with rmarkdown::render(input = "template_datatable.Rmd", output_file = "test.html", params = list(name = "datatable", carat = 5)), the .Rmd with the data.table code works fine.
My questions are.
What is causing this error? And is there a way to fix it?
Here is my code for the .Rmd using data.frames:
---
title: "A report for `r params$name`"
params:
name: "name"
factor: 1
output:
bookdown::html_document2:
fig_caption: yes
toc: yes
toc_float: true
code_folding: "hide"
---
```{r setup, include=FALSE}
# Setup Chunk
# Some knitr options
knitr::opts_chunk$set(echo = FALSE)
# Packages
library(dplyr)
library(ggplot2)
```
```{r dataImport}
df <- data.frame(A = seq(1, 100), B = seq(1, 100))
df <- df %>%
mutate(C = B * params$factor)
```
```{r makePlot}
ggplot(df, aes(A, C)) +
geom_line()
```
And my code for the .Rmd using data.tables:
```
---
title: "A report for `r params$name`"
params:
name: "name"
factor: 1
output:
bookdown::html_document2:
fig_caption: yes
toc: yes
toc_float: true
code_folding: "hide"
---
```{r setup, include=FALSE}
# Setup Chunk
# Some knitr options
knitr::opts_chunk$set(echo = FALSE)
# Packages
library(data.table)
library(ggplot2)
```
```{r dataImport}
dt <- data.table(A = seq(1, 100), B = seq(1, 100))
dt <- dt[, C := B*params$factor]
```
```{r makePlot}
ggplot(dt, aes(A, C)) +
geom_line()
```
Thanks for your help.

Is there a way to add a scroll bar to dfSummary output in R markdown file?

I've already tried using the print function:
print(dfSummary(df), method = "render")
And also all the solutions here but they don't seem to work with html_document as the output file type of the R Markdown.
Olá, Inês
The answer is in provided link. You just need to add max.tbl.height argument and specify height in pixels:
print(dfSummary(df),
max.tbl.height = 250,
method = "render")
Here goes an reproducible example (see # comments for tips & tricks):
---
title: "Title"
author: "Author"
date: "26/05/2020"
output:
html_document:
toc: TRUE
toc_float: TRUE
---
```{r setup, include = FALSE}
library(knitr)
library(summarytools)
knitr::opts_chunk$set(results = "asis")
```
### Adding a scrollbar to dfSummary
```{r summarytools-css, echo = FALSE}
# with summarytools’ CSS we can cancel Bootstrap’s CSS (both are included by default)
# without it odd layout are expected, especially with dfSummary()
st_css(bootstrap = FALSE)
```
```{r dfSummary, echo = FALSE}
print(dfSummary(tobacco,
style = "grid", # set style to “grid”
valid.col = FALSE, # drop Valid column if redundant
graph.magnif = 0.82), # zoom factor (max = 1) for bar plots and histograms
headings = FALSE,
footnote = NA,
# use maximum table (specified) height (in pixels) and wrap the results in a scrollable window
max.tbl.height = 300,
method = "render")
```
If you have interest, check out Dominic's vignette - "Recommendations for Using summarytools With Rmarkdown".
May I suggest using the package "DT", if you absolutely need dfSummary I can try again, but would need the minimal amount of code for replicate your example. DT has search functionality along with letting the user control how many rows they see when viewing the data.
---
title: "DF summary"
author: "stackoverflow"
date: "5/24/2020"
output: html_document
---
```{r}
library(DT)
datatable(head(mtcars, 30), options = list(
order = list(list(2, 'asc'), list(4, 'desc'))
))
```

Display a data.frame with mathematical notation in table header R Markdown html output

Say I'd like to display a table of coefficients from several equations in an R Markdown file (html output).
I'd like the table to look somewhat like this:
But I can't for the life of me figure out how to tell R Markdown to parse the column names in the table.
The closest I've gotten is a hacky solution using cat to print custom table from my data.frame... not ideal. Is there a better way to do this?
Here's how I created the image above, saving my file as an .Rmd in RStudio.
---
title: "Math in R Markdown tables"
output:
html_notebook: default
html_document: default
---
My fancy table
```{r, echo=FALSE, include=TRUE, results="asis"}
# Make data.frame
mathy.df <- data.frame(site = c("A", "B"),
b0 = c(3, 4),
BA = c(1, 2))
# Do terrible things to print it properly
cat("Site|$\\beta_0$|$\\beta_A$")
cat("\n")
cat("----|---------|---------\n")
for (i in 1:nrow(mathy.df)){
cat(as.character(mathy.df[i,"site"]), "|",
mathy.df[i,"b0"], "|",
mathy.df[i,"BA"],
"\n", sep = "")
}
```
You can use kable() and its escape option to format math notation (see this answer to a related question). Then you assign your mathy headings as the column names, and there you go:
---
title: "Math in R Markdown tables"
output:
html_notebook: default
html_document: default
---
My fancy table
```{r, echo=FALSE, include=TRUE, results="asis"}
library(knitr)
mathy.df <- data.frame(site = c("A", "B"),
b0 = c(3, 4),
BA = c(1, 2))
colnames(mathy.df) <- c("Site", "$\\beta_0$", "$\\beta_A$")
kable(mathy.df, escape=FALSE)
```

RMarkdown: bookdown with plotly

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"))
```

Resources