Comments in Rpres - r

I'm trying to put a comment in my Rpres script, but I don't want that comment to appear in the final presentation. I know that in an R script, the comments are expressed by #comment. But how it would be in Rpres?
For example, for a specific slide:
Title of slide:
```{r}
vector <- c(1,2,4)
dataframe <- data[data$line == 4,]
table <- table(dataframe$line2)
```
I want to add a comment here about a code line (this comment would be visible only for me in my Rpres script, but not on the presentation display).
Then I explain the results (this part would be on the presentation display).
Is there a special key like % or # that would make that work?

There is more than one way of doing this, what I found to be fairly generic is the following format:
[//]: # ("this is just a comment")

Related

Use loop to generate section of text in rmarkdown

I need to produce a report that is composed of several sections, all sections look similar, with only some differences in data. The number of sections is also dependent on the data. What I ultimately want to have is something like this:
```{r}
section_names = c("A","B","C")
section_data = c(13,14,16)
```
# some looping mechanism here with variable i
This is section `r section_names[i]`
This section's data is `r section_data[i]`
#more things go here for the section
#end of loop should go here
The result should be a single html/document with all the sections one after the other.
Can you point me to a way for producing such an Rmd file with the loop?
Ideally I would have hoped to see something like in PHP:
<$php for(i=0;i<10;i++) { ?>
## some html template + code chunks here
<$php } ?>
This question is similar to that one, although it is LateX/RNW based. Besides, this answer demonstrates how to generate a rmarkdown document dynamically. However, neither of the questions is a exact duplicate of this one.
Basically, there are two mental steps to take:
Figure out the markdown markup needed per section. This could be something along the lines of
## This is section <section_name>
Section data is `<section_data>`.
Additional section text is: <section_text>.
Write R code that generates this markup, replacing the placeholders with the appropriate values.
For step 2, using sprintf is a natural candidate to combine static and dynamic text. Don't forget to use the chunk options results = "asis" to prevent knitr from adding formatting to your output and use cat (instead of print) to prevent R from adding additional stuff like quotes and element numbers.
I changed the input data structure a little bit for the sake of clarity (using a data.frame instead of independent vectors section_names and section_data).
```{r echo = FALSE, results = "asis"}
input <- data.frame(
name = LETTERS[1:4],
data = runif(n = 4),
text = replicate(4, paste(sample(x = LETTERS, size = 100, replace = TRUE), collapse = "")),
stringsAsFactors = FALSE)
template <- "## This is section %s
Section data is `%0.2f`.
Additional section text is: %s.
" # dont't forget the newline
for (i in seq(nrow(input))) {
current <- input[i, ]
cat(sprintf(template, current$name, current$data, current$text))
}
```
Output:
This is section A
Section data is 0.83.
Additional section text is: PUFTZQFCYJFNENMAAUDPTWIKLBSVKWMJWODFHSPRJRROTVDGNEROBVQPLLMVNPOUUHGVGRPMKAOAOMVYXKMGMUHNYWZGPRAWPYLU.
This is section B
Section data is 0.49.
Additional section text is: PFTYCGFSGSMAYSSCZXWLNLDOQEBJYEVSJIYDJPEPSWQBNWJVRUKBTYIUSTOICFKJFEJCWCAYBCQSRTXUDEQLLXCZNPUKNLJIQJXE.
This is section C
Section data is 0.58.
Additional section text is: FCJDDDMNLBUSJMCZVSBPYWCKSFJEARBXXFPAGBTKCWKHPEDGYWYTNGLVGQGJAFZRUMNSDCHKTTMGRFNSUZKFLOUGNWHUBNLVMGDB.
This is section D
Section data is 0.52.
Additional section text is: YQIXHABFVQUAAYZNWTZXJDISSLTZJJAZOLJMJSXEENFTUOFOTYKDNNUMFDXLJSWZEVDLCLSYCTSMEXFLBVQYRTBEVZLCTEBPUGTT.
Just sharing the approach I've used eventually.
I wrote a markdown file for the section. prepared the data for each section in the master document, and looped over all the sections I needed, each time calling to knit_child() with the section Rmd.
I know this is late, but I used this in my code to make numbered sections and it works a treat.
for (k in 1:length(listcsv)){ #Begin Loop at pdf file one and continue until all have been completed
subsection <- paste("5", k, sep = ".")}
this uses the loop number (k) to create the subsection number and then paste it against the section number. This happens to be in section 5, but you could use the same principle to make sections and subsections ad infinitum.

highlight all inline \Sexpr{} outputs in the generated pdf

I am using knitr for a report wherein I have a lot of inline output text, mostly numeric values, using \Sexpr{}. I want to highlight All these inline outputs in my generated pdf.
Example code:
\documentclass[12pt]{article}
\begin{document}
<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
#
There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.
\end{document}
Hence, in the output all the number should be highlighted, i.e. with a shaded background (similar to using with \hl{} with the \usepackage{soul}).
It seems to me that the solution would use one of the inline output hooks. Another possibility might be to write a LaTeX function which search all the \Sexpr{...} expressions in the entire document and highlights them in the generated pdf. I am still learning and can not figure out how to implement these.
Thanks for any help or hints.
Note: The knitr page by yihui talks about manipulation of the numeric value (scientific notation, digits after decimal points) which I have got covered.
The output hook inline can be used to style output from \Sexpr{}. This is as simple as
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", x)})
Just define an arbitrary function that takes an argument x and returns the string to be printed. In this example I used \textbf to make the output bold, but this can be extended to any LaTeX commands.
In this answer, Yihui suggests an improvement that still takes the default inline hook into account. This ensures rounding as usually performed by the default hook:
hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", hook_inline(x))})

inline Latex code inside knitr R block

I am looking for a way to put inline latex code into a R code chunk in Knitr.
Here is my example code from the knitr example site :
\documentclass{article}
\begin{document}
Example text outside R code here; we know the value of pi is \Sexpr{pi}.
<<my-label, echo=FALSE, eval=TRUE>>=
set.seed(1213) # for reproducibility
x = cumsum(rnorm(100))
m <- mean(x) # mean of x
print(m)
cat(m)
plot(x, type = 'l') # Brownian motion
#
\textit{Mean is :} \textbf{\Sexpr{m}}
\end{document}
For something simple like this is I could use result='asis' but for a more complicated piece of code, where you want to periodically write the result out to the document, (especially you have complex ggplot graphs), that solution does not work very well.
In the given example, I have 3 queries :
How would I use inline latex code for the output from line 8, in case I wanted to color, bold etc. that text.
Can one eliminate the grey box that appears when we use the cat or print command.
Can the numbering which appears with the print command, which is eliminated with the cat command be eliminated for the print command as well, since print has many variants in many packages for data frames data tables etc. and might be more commonly used to print a portion of data.
In summary, I am mainly looking for the inverse of line 12 in the code.
I have also unsuccessfully tried knit_print with printr, and asis_output, in lieu of print. Although I may have been incorrectly using them.
Thanks!

How to write an article with an abstract referencing data that has not yet been calculated?

UPDATE: Seems like my question is actually a very near duplicate of this question
and according to that thread, there is currently no "easy" solution. However, that question is over a year old now, and the time may have changed (one can hope!).
My original question follows:
I'm thinking that I need some kind of mechanism to re-order the text and or R chunks in the document as it is being knit. What I want to be able to do is to write an "article" style document with an abstract and summary at the beginning, before I get into any R code, but that contains "forward"-references to things that will be calculated in the R code.
So my exec summary at the beginning might be
We found a `r final_correlation/100`% correlation between x and y...
but "final_correlation" will be calculated at the back end of the document as I go through all of the steps of the reproducible research.
Indeed, when I read about reproducible research, I often see comments that the documentation can often be better presented out-of programming sequence.
I believe that in other literate programming frameworks the chunks can be tangled into a different order from that in which they were presented. How can I achieve that in knitr? Or is there some other completely different workflow or pattern I could adopt to achieve the outcome I want?
There is no way to define the order to evaluate all the code chunks in knitr at the moment. One idea I can think of is to write the abstract in the end of the article, and include it in the beginning. An outline:
article.Rmd
abstract.Rmd
In article.Rmd:
Title.
Author.
Abstract.
```{r echo=FALSE, results='asis'}
if (file.exists('abstract.md')) {
cat(readLines('abstract.md'), sep = '\n')
} else {
cat('Abstract not ready yet.')
}
```
More code chunks.
```{r}
x <- 1:10
y <- rnorm(10)
final_correlation <- cor(x, y)
```
Body.
```{r include=FALSE}
knitr::knit('abstract.Rmd') # generates abstract.md
```
In abstract.Rmd:
We found a `r final_correlation/100`% correlation between x and y...

Including R help in knitr output

Is it possible to include R documentation in knitr output? When using stock datasets, it would be nice to just include the builtin documentation without having to copy and paste it in. The problem appears to be that ? works by side effect and so there is no "result" in a meaningful sense. For example,
```{r}
?mtcars
```
has no output that is trapped by knitr.
Using help(...,help_type) instead of ? doesn't help either. I've tried:
```{r, results='markup'}
help(mtcars, help_type="text")
```
and
```{r, results='asis'}
help(mtcars, type="html")
```
with the same result. (In the latter case, knitr did trap the output ## starting httpd help server ... done, which is basically just a message about the side effect.)
In other words, is there a way to extract R help in plain text or HTML?
To answer your specific question, "Is there a way to extract R help in plain text or HTML?", the answer would be to use a combination of Rd2HTML or Rd2txt from the "tools" package, with a little bit of help from .getHelpFile from "utils".
For HTML:
tools:::Rd2HTML(utils:::.getHelpFile(help(mtcars)))
For txt:
tools:::Rd2txt(utils:::.getHelpFile(help(mtcars)))
By the sounds of it, though, you should be able to use the function I've linked to in the comment above. For instance, to include the text from the "Description" section of the "mtcars" help page, you would use something along the lines of:
```{r, echo=FALSE, results='asis'}
cat(helpExtract(mtcars, section = "Desc", type = "m_text"))
```
I think you can get what you want by hacking the pager option as follows:
pfun <- function(files, header, title, delete.file) {
all.str <- do.call("c",lapply(files,readLines))
cat(all.str,sep="\n")
}
orig_pager <- options(pager=pfun)
help("mtcars")
options(orig_pager)
(you can return the character vector from the function instead of cat()ing it if you prefer).
Use printr, e.g.
library(printr)
help(mtcars)
detach('package:printr', unload = TRUE)

Resources