GitHub displays all code chunks from README.rmd (despite include=FALSE) - r

I am currently writing a documentation for an R package hosted on GitHub. I use knitr along with R Markdown to write the README file. Hitting the 'Knit HTML' button in RStudio produces an HTML like I would expect it.
However, pushing README.rmd to GitHub results in what you see in the lower page section when following the above link. For example, the topmost code chunk is declared as follows in the README.rmd file:
```{r global_options, include = FALSE}
library(knitr)
options(width = 120)
opts_chunk$set(fig.width = 12, fig.height = 8, fig.path = 'Figs/',
include = TRUE, warning = FALSE, message = FALSE)
```
However, the include = FALSE statement in the first line of code is simply ignored in this case, and the piece of code that was supposed to be hidden is displayed on the referring GitHub page. In addition, results (e.g. from plot(), head()) are not visualized although opts_chunk$set(..., include = TRUE).
Did anyone encounter a similar problem and can me help me get my README document displayed correct, i.e. in the way RStudio would handle it, on GitHub?

The readme file you are trying to publish on github should be a plain markdown document i.e., a .md file and not the raw .rmd. So first you knit the .rmd with knitr (within R) as follows:
knit(input="readme.rmd", output = "readme.md") #see ?knit for more options
That will evaluate the global and chunk options specified in the source .rmd and produce a .md that's formatted accordingly and which github can render readily.

For more information on using an .Rmd to generate the .md see the Readme.Rmd section of http://r-pkgs.had.co.nz/release.html
You can also have devtools set up this automatically for your package using devtools::use_readme_rmd().

Related

Change option settings with knit:pagedown::chrome_print in Rmarkdown YAML

I have created a large R Markdown document with many child docs using RStudio to produce output in both HTML and PDF.
I added this simple line to the YAML parameters of the document and it does exactly what I need. The entire doc is rendered and saved as both html and pdf output. Formatting of complex tables is preserved nicely.
knit: pagedown::chrome_print
BUT - the pdf is oversized. It simply needs to be scaled to 0.8 to be really useable. chrome_print documentation says that scale can be adjusted within the chrome_print command. I've tried this:
knit: pagedown::chrome_print(scale = 0.8)
which produces an Execution Halted error. I have tested other ways to pass parameters through the render to chrome_print, but none work.
The question is simple: Is there a way to pass parameters into the knit: pagedown::chrome_print operation?
After much experimentation, I find there is currently no way to adjust any pdf options from within R markdown YAML using knit: pagedown::chrome_print.
The workaround I've found is to use the code chunk below to render the Rmarkdown. It saves to both html and pdf formats and allows the user to assign filenames. Note that scaling does not adjust pagination nicely without CSS reset as shown. This works great, and allows full use of rmarkdown parameters and all chrome_print options.
fname = "OutputFilename"
pagedown::chrome_print(
rmarkdown::render(
input = "input.Rmd",
output_file = paste0(fname, ".html"),
output = paste0(fname, ".pdf"),
options = list(scale = 0.7, preferCSSPageSize = FALSE))

issues knitting R markdown to pdf with psych package

The issue I'm having is after I knit my R-Markdown file to a pdf (or word) document, I get the following error:
However, I have made sure the I have my library(psych) call in my r in which the code chunks are being called from. The describe() call works just fine when I call it in my .r file in r studio, and when I call it inline in the markdown file, but I still get the error when I knit to pdf.
Knitr code referenced in .r file.
## #knitr code_2.2
library(psych)
describe(women_DF)
code chunk in r markdown:
## 2.2 Summarize using describe()
* The `summary` function in base R does not show the number of observations and standard deviation of each variable
+ A convenient alternative to `summary` that includes these statistics is `describe` in the `psych` package
* If you have not already done so, install the `psych` package
+ Console: install.packages("psych") or from Packages → Install dialog
* Recall that you must also call `library(psych)` to load the package into memory
* Now use `describe()` to summarize `women_DF`:
```{r code_2.2}
Setup of r markdown file:
---
title: "Module 1 Workshop"
author: "MSBX-5310 (Customer Analyitcs)"
date: "1/14/2021"
output:
pdf_document: default
word_document: default
---
```{r, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
fig.height = 3,
fig.width = 4,
message = FALSE,
comment = NA, error = TRUE)
#uncomment the line below if using an external R script for R chunks
knitr::read_chunk("Workshop1.R")
knitr runs code in its own R session when you click the knit button. This means that anything you have in your environment is not available to that separate session building your document.
In particular, although you did not post your entire Rmarkdown file, it seems the problem is that you didn't load the psych package anywhere in your .Rmd file. You shoould load it somewhere in the Rmarkdown file, either in a separate chunk (if you don't want it to show just before your function call) or in the same chunk where you call one of its functions (in this case, describe()).
```{r code_2.2}
library(psych)
describe(women_DF)

run an R Markdown (check.Rmd ) and an R knitr (test.Rnw ) file together

I have the following problem; There are 2 big documents, one written in R Markdown (check.Rmd ) and the other in R knitr (test.Rnw ). In the first doc we have a code like the following:
\section{Organisations Test}
\textbf{Running Organisations Checks}
<<CreateOrganisations, echo=FALSE, progress=TRUE, warning=FALSE, eval=TRUE>>=
source("OrganisationsTest.R")
OrganisationsTest(current_schema,server,user,pass)
#
and in the other as follows:
2. check the downwards shock
```{r chunk_Int_Sh_p2, echo=FALSE}
unique(param.int.shock.tab[SHOCKTYPE=="SHOCK_DOWN"&PERIODEND<21|PERIODEND==90, list( Maturity=PERIODEND, Shock_value=100*SHOCKVALUE)])
```
Now the question: how can I combine both so that I have just one script which runs and compile both one after each other. Just for clarification, I mean without any changes in both documents how can I have just one script which applyes to the first doc knit PDF to create pdf and to the other one CompilePDF ?
I suppose in Linux one can write a shell script but what a bout using RStudio in windowes?
I am really grateful for every hint I am a little bit helpless!
Addendum: In principle it is as follows: we have 2 files if you would compile a knitr file you would use bottom in RStudio, and for a Markdown file one may use bottom in RStudio, BUT we want to put both together and klick on one bottom. How is it possible?
The RStudio buttons "Compile PDF" (for RNW documents) and "Knit PDF" (for RMD documents) are convenient, but in cases like this one it is important to understand what they do in order to reproduce the same or similar behavior.
Summing the question up, it asks for a way to convert two files (a RMD and a RNW document) to PDF, preferably using a button like the two buttons mentioned above.
Unfortunately, (up to my knowledge) it is not possible to add any user-defined buttons to the RStudio GUI. But it is straightforward to write an R script that compiles both documents.
In the following I assume two files:
first.Rmd:
This is a RMD file.
```{r, echo=FALSE}
plot(1)
```
second.Rnw:
\documentclass{article}
\begin{document}
This is a RNW file.
<<>>=
plot(1)
#
\end{document}
To compile first.Rmd to PDF, we need the following (see How to convert R Markdown to PDF?):
library(knitr)
library(rmarkdown)
knit(input = "first.Rmd")
render(input = "first.md", output_format = "pdf_document")
The knit call generates first.md from first.Rmd, execting the R code in the chunks. render converts the resulting markdown file to PDF. [Note the addendum at the bottom!]
To compile first.Rnw to PDF, we can simply use knit2pdf:
knit2pdf("second.Rnw")
Copying both snippets into one R script and clicking "Source" is as close as possible to a "one-button-solution".
However, note that the snippets do something very similar to the "Compile / knit PDF" button, but it is not identical. The "Compile" buttons start a new R session while the solution above uses the current session.
Before executing the snippets make sure to use the correct working directory.
Both knit and knit2pdf by default use envir = parent.frame(). That means R code in chunks is executed in the calling enironment (see What is the difference between parent.frame() and parent.env() in R). This can be a useful feature, for example to "pass" variables to chunks, but it is important to know about it. Otherwise a document might compile just fine in one session (where certain variables exist in the calling environment) but cannot be compiled in another session (that is missing these variables). Therefore, this feature is a little bit dangerous in terms of reproducibility. As a solution, envir = new.env(parent = as.environment(2)) could be used; see knitr inherits variables from a user's environment, even with envir = new.env() for more details on that topic.
I just realized to following about render:
If the input requires knitting then knit is called prior to pandoc.
(Source: ?render)
Therefore, knit(input = "first.Rmd"); render(input = "first.md", output_format = "pdf_document") can be simplified to render(input = "first.Rmd", output_format = "pdf_document"). The envir issues of knit from above apply to render as well.

Issue creating model summary table using package texreg with RStudio/rmarkdown/knitr

I'm using the RStudio IDE (v 0.99.323) with rmarkdown and am attempting to produce model tables via knitr using htmlreg to produce MSWord output. Suspect I've missed something simple.
The rmarkdown chunk appended below creates a separate word file 'mytable.doc' with a beautiful table. However, when I click 'Knit Word' in the RStudio IDE, the line htmlreg(m) generates html table code in the MSWord document. What am I doing wrong?
Many thanks! --Dale
```{r, results='asis'}
library(MASS)
library(texreg)
data(menarche)
m <- glm(cbind(Menarche, Total-Menarche) ~ Age, family=binomial(logit), data=menarche)
htmlreg(m, file = "mytable.doc", caption="Age at Menarche", inline.css = TRUE, doctype = TRUE, html.tag = TRUE, head.tag = TRUE, body.tag = TRUE, ci.force=TRUE, ci.test=NULL,bold=TRUE)
htmlreg(m)
```
Try this in your chunk, still using result='asis':
library(pander)
pander(m)
Hat tip to http://www.r-statistics.com/2013/03/write-ms-word-document-using-r-with-as-little-overhead-as-possible/
They also suggest a nice way to clarify code chunks so that you can just call print(m) and the output in markdown will call the appropriate function from pander.
Can you please try the latest texreg version 1.34.2 (see the .tar.gz file here or in this post)?
According to the RStudio developers, the problem is that they switched to a newer version of Pandoc, which does not work with indented HTML code anymore. More precisely, it interprets text that was indented with four spaces as a code block, as in Markdown notation. See here for their problem description.
So in the new texreg version, there is a new argument called indentation = "" in the htmlreg function. It switches indentation off by default. Using indentation = " " restores the previous behavior.
Edit 1: Please also make sure to use arguments center = FALSE and star.symbol = "\\*" for alignment on the left and for displaying significance stars correctly. Asterisks need to be escaped because they are otherwise interpreted as part of the Markdown syntax:
```{r, results = 'asis'}
htmlreg(m, center = FALSE, star.symbol = "\\*")
```{r}
For PDF notebooks (which use LaTeX internally), use texreg:
```{r, results = 'asis'}
texreg(m, float.pos = "h")
```{r}
Edit 2: Also read the help page of htmlreg, especially the part where the arguments of htmlreg are described. They contain some useful information on how to make the documents as compatible as possible with Markdown, which is used by RStudio, Pandoc, and knitr to create HTML documents. In particular, use arguments inline.css = TRUE, doctype = FALSE, html.tag = FALSE, head.tag = FALSE, and body.tag = FALSE when you do not intend to create a full-fledged HTML document.
About MS Word: You mentioned in a comment below your question that you wanted to create either HTML or Word documents. The htmlreg function is intended to create HTML files, not Word files (as the name of the function implies). It is possible to load these HTML files in MS Word, though, because Word is able to interpret HTML code. However, knitr creates binary Word documents, and embedding HTML code directly in these binary Word documents is not possible, as far as I know (but I may be wrong because I don't know how knitr creates the Word files internally). You could, however, try to create HTML notebooks, save them to disk, and then open them in MS Word.
This is a problem of pandoc markdown, or of htmlreg not creating the correct indentation. I do not fully understand if this is a bug or a feature because of the cryptic:
http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html#raw-html
Try a simple .md (not .rmd) file as follows:
<h1>Works</h1>
<table border="8">
<tr>
<td>111</td>
<td>222</td>
<td>444</td>
</tr>
</table>
<h1>Not what you want</h1>
<table border="8">
<tr>
<td>111</td>
<td>222</td>
<td>444</td>
</tr>
</table>
<h1>Works too (not in screenshot)</h1>
<table border="8">
<tr><td>111</td><td>222</td><td>444</td></tr>
</table>
The package author has updated texreg to switch-off indentation by default.
See:
http://rmarkdown.rstudio.com/authoring_migrating_from_v1.html#preserving-generated-html
after updating the package via:
install.packages("texreg", repos = "http://R-Forge.R-project.org")
The chunk below placed in an rmarkdown (.Rmd) document now produces a beautiful html table when I 'Knit HTML' within RStudio. However, 'Knit Word' still does not produce the expected output.
```{r, results='asis'}
library(texreg)
htmlreg(m, caption="Age at Menarche", caption.above=TRUE, ci.force=TRUE, ci.test=NULL,bold=TRUE)
```

Dynamic LaTeX references in R comment with knitr

I had ask a similar question to this with respect to Sweave (
Dynamic references to figures in a R comment within Sweave document
) and would like to see if anyone as a similar answer when using knitr.
The goal is to have the following code chunk
<<"example", fig.cap = "some figure", highlight = FALSE>>=
# the following code generated Figure \ref{fig:example}
plot(1:10, 1:10)
#
have be displayed in the resulting .pdf as
# the following code generated Figure 1.1
plot(1:10, 1:10)
So far I have found that by setting highlight = FALSE the R code is placed into a verbatim environment in the resulting .tex file. If the environment could be alltt instead of verbatim then we'd have the desired output. Is it possible to have the non-highlighted code chunks be placed in alltt environments via a knitr option?
I have added an example 072-latex-reference.Rnw in the knitr-examples repository. The basic idea is to restore the escaped \ref{} (which should have been \textbackslash{}ref\{\} in the default output).

Resources