RMarkdown conversion - r

---
title: "Twitter Data processing"
author: "Ankur"
date: "7 September 2016"
output: pdf_document
---
```{r setup, include=FALSE}
library(knitr)
library(SnowballC)
library(tm)
library(ggplot2)
library(RColorBrewer)
library(wordcloud)
```
"SnowballC" is required for stemming the document in this particualr verion. You may alternatively need "Snowball".
```{r Turning into Corpus, include=TRUE, warning=FALSE}
myCorpus<-tm_map(myCorpus, stemDocument)
writeLines(strwrap(myCorpus[[250]]$content,60))
```
I am having issues while knitting the RMD Document. the code works fine but it is not building the RMD file. I have the "myCorpus" variable in other file, butr it is loaded into an environment. I am having the following error:
Error in tm-map(myCorpus, stemDocument) : object ;myCorpus' not found
calls:<Anonymous> ... withCallingHandlers -> withVisible -> eval-> eval ->tm_map Execution Halted

There are 2 ways to load the data "myCorpus" to your .RMD file:
library(knitr)
knit('your_file.Rmd')
This will take your recent environment into account and the error should be gone.
Store your "myCorpus" as "myCorpus.RData" and load it manually in your RMD file
```{r load myCorpus, include=FALSE}
load("myCorpus.RData")
If you do it this way you can use the "knit" button from RStudio.
I hope one of this ways is a good solution for you.

Related

Adding a leaflet in a precompile vignette

I'm maintaining R code in my company that is use by multiple colleagues. I decided to convert my code into a package to make it simpler to share, maintain and document. My package is build to stay internal, be used in a close environment and is not going to be on CRAN. I'm using Rstudio and it's going relatively well but I hit a problem when building vignettes.
The problem is that my code makes very specific, long and complex analysis on very big datasets. It's therefore not possible for me to have the vignette built every time I rebuilt the package. Even less having the user do it when using devtools::install_git(build_vignettes = TRUE). I've found a solution to this problem in this nice blog (https://ropensci.org/blog/2019/12/08/precompute-vignettes/). Briefly, you add .orig after your vignettes names .Rmd so they are not identified as vignette by the build process. Then, when you are ready, you precompile your script by knitting your .Rmd.orig file with:
knitr::knit("vignettes/longexample.Rmd.orig", output = "vignettes/longexample.Rmd")
This will create a quick and easy compilable version of your vignette for your package. This works for basic document with text and figures. However, I need to enter a leaflet map into my vignette. If I use this process to create my vignette with a leaflet, I get an error:
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
## Error in path.expand(path): invalid 'path' argument
I think this is a message showing that knitr is trying to get a screenshot of my map to save it as an image. This is not what I want, I want an actual map.
Reproducible example
The vignette I wrote:
---
title: "Example"
author: "BastienFR"
date: "09/05/2022"
output: html_document
---
```{r setup, message=F, warning=FALSE}
library(leaflet)
```
## Intro
A simple and slow example of vignette with a `leaflet`
## The slow part
```{r}
time <- 2
Sys.sleep(time)
message("I've waited this long!")
```
## The leaflet
```{r}
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
```
```{r}
m
```
Then, I compile it with :
knitr::knit("c://temp//longexample.Rmd.orig", output = "c://temp//longexample.Rmd")
which produce this output:
---
title: "Example"
author: "BastienFR"
date: "09/05/2022"
output: html_document
---
```r
library(leaflet)
```
## Intro
A simple and slow example of vignette with a `leaflet`
## The slow part
```r
time <- 2
Sys.sleep(time)
message("I've waited this long!")
```
```
## I've waited this long!
```
## The leaflet
```r
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
```
```{r}
m
```
```
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
```
```
## Error in path.expand(path): invalid 'path' argument
```
So, it's not able to pass along the leaflet into the new knit markdown file (which makes sense).
I tried to bypass this problem by saving the leaflet into a temporary file like this (in my .orig file):
```{r, include=FALSE}
saveRDS(m, "c://temp/temp_leaflet.rds")
```
This would save my map, but then I have to find a way to add the next code block in the compiled version, so it appears and it's run only there. Some way to have the code block below passed as-is by knitr.
```{r, include=FALSE}
m <- readRDS("c://temp/temp_leaflet.rds")
```
So I'm stuck. Any idea how to display a leaflet into a markdown/vignette after a precompilation?
This problem can be fix by having knitr knit "asis" the lines of code you want to knit in the second run, so when building the vignette... To do this, you can change the section:
```{r}
m
```
by:
```{r, echo=FALSE}
saveRDS(m, "c://temp/temp_leaflet.rds")
```
```{r, eval=T, results="asis", echo=FALSE}
cat("```{r, echo=FALSE, warning=FALSE} \n")
cat("library(leaflet) \n")
cat("m <- readRDS('c://temp/temp_leaflet.rds') \n")
cat("```")
```
```{r, eval=T, results="asis", echo=FALSE}
cat("```{r, echo=TRUE} \n")
cat("m \n")
cat("```")
```
Explanation
First, you save your map (or data) somewhere in an rds file. Then, you use the results="asis" code block option and the cat function to write the code block that you need rendered only the in the second compilation (when the vignettes are build). So you are actually wrapping Rmarkdown code into Rmarkdown... It's ugly and confusing, but it works. Using this approach, the render code after knitting the Rmd.orig file looks like normal Rmarkdown code:
```{r, echo=FALSE, warning=FALSE}
library(leaflet)
m <- readRDS('c://temp/temp_leaflet.rds')
```
```{r, echo=TRUE}
m
```
It will then be perfectly render in your vignettes.
The only complication now is to manage the save and read location of the rds file because markdown and vignettes can have tricky working directories.
So the final .orig file is now:
---
title: "Example"
author: "BastienFR"
date: "09/05/2022"
output: html_document
---
```{r setup, message=F, warning=FALSE}
library(leaflet)
```
## Intro
A simple and slow example of vignette with a `leaflet`
## The slow part
```{r}
time <- 2
Sys.sleep(time)
message("I've waited this long!")
```
## The leaflet
```{r}
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
```
```{r, echo=FALSE}
saveRDS(m, "c://temp/temp_leaflet.rds")
```
```{r, eval=T, results="asis", echo=FALSE}
cat("```{r, echo=FALSE, warning=FALSE} \n")
cat("library(leaflet) \n")
cat("m <- readRDS('c://temp/temp_leaflet.rds') \n")
cat("```")
```
```{r, eval=T, results="asis", echo=FALSE}
cat("```{r, echo=TRUE} \n")
cat("m \n")
cat("```")
```

Execution halted when knitting in RStudio

I´m new at R. I was trying to knit a Rmd file in RStudio into a pdf, but it presents the following error:
Quitting from lines 17-20 (projeto_final_20220429.Rmd)
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> View
Execution halted
The code written in those lines was this:
library(readr)
despesas_municipios_saude_educacao <- read_csv("despesas_municipios_saude_educacao.csv")
View (despesas_municipios_saude_educacao)
Is there anyone who can help me?
On MacOS, knitr attempts to load the X11 library in order to view the data frame, which fails because knitr isn't designed to interact with an end user. Regardless of the underlying operating system, since utils::View() is meant to work in a windowing environment (e.g. RStudio, RGui, R Tools for Visual Studio, etc.), it can't be used to print a data frame in an R Markdown document.
---
title: "Error with View()"
output: html_document
date: "`r Sys.Date()`"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## A header
Here is a reproducible version of the stackoverflow question [Execution Halted when Knitting](https://stackoverflow.com/questions/72068679/execution-halted-when-knitting-in-rstudio).
```{r mtcars}
data(mtcars)
View(mtcars)
```
...generates the following error:
To display a subset of data in a markdown file, one can use head() instead of View().
---
title: "Error with View()"
output: html_document
date: "`r Sys.Date()`"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## A header
Here is a reproducible version of the stackoverflow question [Execution Halted when Knitting](https://stackoverflow.com/questions/72068679/execution-halted-when-knitting-in-rstudio).
```{r mtcars}
data(mtcars)
head(mtcars)
```
...and the output in HTML:
We can improve the look of the output by turning off echo on the R chunk used to print the table, and use knitr:kable() to format the data frame.
We use the following R Markdown code, including the "pipe" argument to appropriately space the columns in the output.
We can make the output look nicer with `knitr::kable()`.
```{r kableVersion,echo=FALSE}
library(kableExtra)
kable(head(mtcars),"pipe")
```
...and the output renders like this in HTML:

`knitr::include_url` ignored in output

After updating R to version 3.6.0, and re-installing the required packages, knitting Rmd documents now seems to ignore the knitr::include_url function.
The following is a minimal example, in a file named test.Rmd -
---
title: "test"
author: "Michael Dorman"
date: "May 1, 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
knitr::include_url("https://www.wikipedia.org/")
```
```{r}
knitr::include_graphics("https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png")
```
And here is a screenshot of the output, after pressing Knit in Rstudio -
The knitr::include_url function is ignored. No <iframe> element was produced. The knitr::include_graphics function still works, so the image does appear in the output.
Thanks for reading, I appreciate any help!

Using knitr to create HTML slides and separate R code file

Following on from this question... I am not sure where to set knitr option if I want to output a separate file of R code. The following does not provide the expected additional .R files in my working directory.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library("knitr"); purl("myfile.rmd")
#library("knitr"); knit("test_tangle.Rmd", tangle = TRUE)
#opts_knit$set(tangle=TRUE)
```
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
but an error message...
Quitting from lines 6-7 (myfile.rmd)
Error in readLines(if (is.character(input2)) { :
cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> purl -> knit -> readLines
Execution halted
I recommend you to use the hook_purl function instead. The function purl() (or equivalently, knit(tangle = TRUE)) may fail to work in certain cases, and the hook function hook_purl() is more reliable. See ?hook_purl for more information.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library("knitr")
knit_hooks$set(purl = hook_purl)
```
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
Then as you knit the document, the R script will be automatically generated.

add latex to rmarkdown to wrap long lines using listings package

Long urls do not break when knitting to PDF in RStudio. This can be solved with the listings package if using .Rnw, but I'm not sure what can be done if using RMarkdown.
It seems like it's possible to include some LaTeX commands, but I have not figured out a way to implement the listings solution in .Rmd.
I tried:
---
title: "my title"
header-includes:
- \usepackage{listings}
output:
pdf_document
---
render_listings()
```{r setup, include=FALSE}
library(knitr)
render_listings()
```
```{r url, include=TRUE}
url <- "https://raw.githubusercontent.com/yihui/knitr-examples/master/066-listings-breaklines.Rnw"
```

Resources