Accessing data generated by an R script with r markdown and knitr - r

I am new to R markdown and knitr and haven't found the answer to this question:
I have R scripts where I've written functions and have assigned data to position 1 (.GlobalEnv). How do I access my data and run my functions within R markdown and generate the .html file with knitr?
Here's a trivial example. In a script file I generate:
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
toy.fn() works in the script file.
My R markdown file contains:
---
title: "trivial test"
author: "me"
date: "July 9, 2015"
output: html_document
---
```{r}
plot(some.x.data, some.y.data)
toy.fn()
```
When I click knit HTML, I get the following error:
Error in plot(some.x.data, some.y.data) : object 'some.x.data' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> plot
Thanks

RStudio opens a new R session to knit() your Rmd file, so the objects in .GlobalEnv will not be available to that session (they are two separate sessions), so when you are knitring HTML there is not way to know what some.x.data, some.y.data and toy.fn is.
Either you need to recreate them in your Rmd file. If you don't want any output just do:
```{r, echo = FALSE, message = FALSE}
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
```
Full Rmd:
---
title: "trivial test"
author: "me"
date: "July 9, 2015"
output: html_document
---
```{r, echo = FALSE, message = FALSE}
some.x.data<-1:10
some.y.data<-1:10
toy.fn<-function(){
tot<-some.x.data + some.y.data
tot
}
```
```{r}
plot(some.x.data, some.y.data)
toy.fn()
```
Or
knit manually by yourself: library(knitr); knit('your_file.Rmd')

Related

R Markdown code chunk does not show math equations

Basically i want to build a random multiple choice question generator with R Markdown. For this task there need to be equations in the code chunks of the markdown.
The following works like a charm and gives the equation "greekbeta = 1"
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
"$\beta = 1$"
```
In contrast, this will not work when some other math symbol is used, for example:
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
"$\sum_{n=1}^{\infty}$"
```
After pressing knit, an error occurs (unfortunately the error message is in german, basically this: "'\s' is an unknown escape-sequence within the string starting with "$/s"").
I am very puzzled by this, especially because for example \frac{1}{2} works, but \hat{x} does not. Equations in the "normal" markdown text are no problem at all. But for my task, the equations have to be in the code chunk sections.
Does someone has a workaround for this problem? I tried using "$\hat{x}$" or even "$$\hat{x}$", but the error message is still the same.
I am using pandoc 2.11.4, R 4.1.0 and knitr 1.33
Use cat() and escape the escapes.
---
title: "test"
author: "me"
output:
word_document: default
---
```{r eval=TRUE, echo=FALSE,results = "asis"}
cat("$\\beta = 1$", '\n\n')
cat("$a^2+b^2 = c^2$", '\n\n')
cat("$\\sum_{n=1}^{\\infty}x_i$", '\n\n')
```

R: How to knit pdf and only printing output but suppress messages without `suppressMessages`?

---
title: 'title'
author: "author"
output: pdf_document
---
Consider this function:
doSomething <- function() {
message("a message")
2
}
And if I put that inside an R Markdown document:
doSomething ()
Then the output in the PDF will contain both the "a message" and the value 2 once knitted from RStudio. How do I suppress the "a message" without using the suppressMessage function?
```{r, message=FALSE}
doSomething ()
```
See https://yihui.org/knitr/options/ for more info.

R Studio Knitr PDF Markdown prints "asis"

I am generating a PDF document using Knitr. I am calling my r script from a separate file. Everything prints out fine in the PDF, but when I output a table using Stargazer, knitr generates a new page in the PDF document with "asis" printed on the page. I included a screen shot. Any ideas why this is happening?
My code chunk:
---
title: "PALS Biomarker Analysis"
author: "Daniel Parker"
date: "November 20, 2017"
output: pdf_document
header-includes:
- \usepackage{caption}
---
\captionsetup[table]{labelformat=empty}
```{r echo=FALSE}
library(knitr)
read_chunk('11-20-17 PALS Analysis V3.R')
```
```{r eighth, echo = FALSE, results="asis"}
<<linear_model_one>>
```
If I remove the results="asis" the table does not print correctly.
Try changing this code
```{r eighth, echo = FALSE, results="asis"}
<<linear_model_one>>
```
to this (remove the double quotes surrounding asis)
```{r eighth, echo = FALSE, results='asis'}
<<linear_model_one>>
```

How can I run a .RMD (Rmarkdown) file in bash script? [duplicate]

I'm running a markdown report from command line via:
R -e "rmarkdown::render('ReportUSV1.Rmd')"
This report was done in R studio and the top looks like
---
title: "My Title"
author: "My Name"
date: "July 14, 2015"
output:
html_document:
css: ./css/customStyles.css
---
```{r, echo=FALSE, message=FALSE}
load(path\to\my\data)
```
What I want is to be able to pass in the title along with a file path into the shell command so that it generates me the raw report and the result is a different filename.html.
Thanks!
A few ways to do it.
You can use the backtick-R chunk in your YAML and specify the variables before executing render:
---
title: "`r thetitle`"
author: "`r theauthor`"
date: "July 14, 2015"
---
foo bar.
Then:
R -e "thetitle='My title'; theauthor='me'; rmarkdown::render('test.rmd')"
Or you can use commandArgs() directly in the RMD and feed them in after --args:
---
title: "`r commandArgs(trailingOnly=T)[1]`"
author: "`r commandArgs(trailingOnly=T)[2]`"
date: "July 14, 2015"
---
foo bar.
Then:
R -e "rmarkdown::render('test.rmd')" --args "thetitle" "me"
Here if you do named args R -e ... --args --name='the title', your commandArgs(trailingOnly=T)[1] is the string "--name=foo" - it's not very smart.
In either case I guess you would want some sort of error checking/default checking. I usually make a compile-script, e.g.
# compile.r
args <- commandArgs(trailingOnly=T)
# do some sort of processing/error checking
# e.g. you could investigate the optparse/getopt packages which
# allow for much more sophisticated arguments e.g. named ones.
thetitle <- ...
theauthor <- ...
rmarkdown::render('test.rmd')
And then run R compile.r --args ... supplying the arguments in whichever format I've written my script to handle.

Using DiagrammeR in Word document (generated using rMarkdown)

I've been looking at the diagrammeR package (http://rich-iannone.github.io/DiagrammeR/) to generate diagrams in rMarkdown. This works great when rendering the documents in HTML; now the question I have is whether there is a possibility to output the document as MS Word document?
For example, consider this:
---
title: "Test"
author: "Test"
date: "Monday, May 18, 2015"
output: html_document
---
```{r, echo=FALSE, warning=FALSE}
if (!require("DiagrammeR")) library("DiagrammeR")
```
Check out this diagram:
```{r, echo=FALSE, results='asis'}
DiagrammeR::grViz("
digraph rmarkdown {
node [shape = box ]
'A' -> 'B'
}
")
```
Using HTML as output format works like a charm. But, when I switch to MS Word, all I get is:
Error: Functions that produce HTML output found in document targeting docx output.
Please change the output type of this document to HTML.
Any ideas would be appreciated.
Many thanks, Philipp
trelliscope is useful: https://github.com/tesseradata/trelliscope
After installing http://phantomjs.org/download.html,
You can generate word doc file by:
---
title: "Test"
author: "Test"
date: "Monday, May 18, 2015"
output: word_document
---
```{r include=FALSE}
if (!require("DiagrammeR")) library("DiagrammeR")
library(trelliscope)
```
Check out this diagram:
```{r, include=FALSE}
p = DiagrammeR::grViz("
digraph rmarkdown {
node [shape = box ]
'A' -> 'B'
}
")
widgetThumbnail(p, paste0(getwd(), "/hoge.png"))
```
![](hoge.png)
Here is the screenshot. It looks perfect :)

Resources