I am creating an Rmarkdown document.
My code chunk checks for the number of columns/rows in the dataset and saves the information in a variable.
{r, echo=FALSE, warning=FALSE}
df_dimenzions <- dim(demo)
I want to use the data/information stored in the variable in the rmarkdown text.
For example... outside of the code chunk, to write plain text such as:
The number of columns is {{df_dimensions[1]}} and the number of rows
is {{df_dimension[2]}}
Is something like this possible in rmarkdown? Again, I'm asking for data that is processed within the rmarkdown, not stored outside of the document?
Also, I am aware that I can paste a concatinated string with the code-chunk. That is not what I am trying to achieve.
Use `r df_dimensions[1]` in the main text.
Related
I'm having a problem with assigning LaTeX environments within an RMarkdown for-loop code-chunk.
In short, I've written an R Markdown document and a series of R-scripts to automatically generate PDF reports at the end of a long data analysis pipeline. The main section of the report can have a variable number of sections that I'm generating using a for-loop, with each section containing a \subsection heading, a datatable and plot generated by ggplot. Some of these sections will be very long (spanning several pages) and some will be very short (~1/4 of a page).
At the moment I'm just inserting a \pagebreak at the end of each for-loop iteration, but that leaves a lot of wasted space with the shorter sections, so I'm trying to "group" each section (i.e. the heading, table and chart) so that there can be several per page, but they will break to a new page if the whole section won't fit.
I've tried using a figure or minipage environment, but for some reason those commands are printed as literal text when the plot is included; these work as expected with the heading and data table, but aren't returned properly in the presence of the image.
I've also tried to create a LaTeX samepage environment around the whole subsection (although not sure this will behave correctly with multi-page sections?) and then it appears that the Markdown generated for the plot is not interpreted correctly somewhere along the way (Pandoc?) when it's within that environment and throws an error when compiling the TeX due to the raw Markdown ![]... image tag.
Finally, I've also tried implementing \pagebreak[x] and \nopagebreak[y] hints at various points in the subsection but can't seem get these to be produce the desired page breaking behaviour.
I've generated an MWE that reproduces my issues below.
I'd be really grateful for any suggestions on how to get around this, or better ways of approaching "grouping" of elements that are generated in a dynamic fashion like this?
---
title: "Untitled"
author: "I don't know what I'm doing"
date: "26/07/2020"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, dev = "cairo_pdf")
```
```{r cars, results='asis'}
for (i in 1:5){
cat("\\begin{figure}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("\\end{figure}")
}
```
Edit to add: interestingly these figure and minipage environments seems to work as expected when executing the same example in an .Rnw using knitr... so does that narrow it down to an issue with Pandoc? Again, any help much appreciated!
What happens is that the raw TeX commands are not treated as TeX when going through Markdown. You can fix that by explicitly marking the relevant snippets as LaTeX:
for (i in 1:5){
cat("`\\begin{figure}`{=latex}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("`\\end{figure}`{=latex}")
}
See the generic raw attribute section in the pandoc manual for details.
I am trying to write a markdown document where I have a chunk of R code within a theorem or example extension.
I assumed I could simply write the theorem extension, starting and ending with ``` and within define an R code chunk starting with ```{r} and ending with ```. As follows:
```{theorem, name="Test"}
Some initial text.
```{r}
a <- 1 + 1
print(a)
And some more text.
However, it seems markdown gets confused, as does stackoverflow, by closing the theorem chunk using the end of the R code block instead of nesting the blocks. Any ideas on how to solve this?
You can't nest chunks like that in r-markdown. You'll need to close your first chunk then open a new one for the R chunk.
Not even sure if this is possible, but is there a way to extract only the raw text portion of the .Rmd file and discard any code?
Or basically converting an .Rmd file into .txt file within R?
I've tried the function readLines, but this makes a huuuuuge character with all kinds of (to me) useless meta-data.
You can knit document without evaluating and including code.
Here's an example of dummy document foo.Rmd:
# Header 1
foo
## Header 2
bar
## Header 22
foobar
```{r}
1
```
text text text
```{r}
print(2)
```
We can knit this document using knitr::knit("foo.Rmd"), but in this case code chunks will be included in text. To deal with this we need to set knitr options:
library(knitr)
opts_chunk$set(list(echo = FALSE, eval = FALSE))
knit("foo.Rmd")
This command will create output document foo.md only with text.
Unfortunately I'm running into some kable trouble when knitting to Word.
In an RScript I've created a function which reads a .csv file, merges this data frame with another existing data frame, calculates a ratio between two of the columns, subsets the merged data frame based on Sample Number and finally merges it with a third data frame containing the true value for that group of samples.
At the end of the function I am using: kable(finalDF).
In an Rmd document, I then apply the function and fill in the variables. The function works and gives the desired result when I run it from within the Rmd document. However, when I knit the document, my table doesn't appear (nothing appears). If I use print(kable(finalDF)) this of course just prints all the text but does not retain the table format. (I also am not running this in a for loop so print shouldn't be necessary).
In my Rmd chunk I DO have {r, echo=FALSE, results='asis' which I know is necessary.
Checking the typeof data frame says it is a list.
Checking the class indicates it is a data.frame.
Why I am utterly bewildered is I have another function elsewhere which is the same typeof and class and has the same commands for the chunk and knitr::kable works just fine for it! I see the table output to word perfectly.
Any thoughts or suggestions with what could be up would be appreciated. Eg. I couldn't find anything that said you couldn't subset and then use kable or that merging two data frames and trying to output using kable caused problems down the line etc.
Relevant chunk appears as:
{r, echo=FALSE, warning=FALSE, results='asis', comment=NA}
HPC<-controlFind("20160114 Mix.csv", "20160114 Mix Controls.csv", "CBHP", 500, "Mix3", 5, "HPC")
I am preparing a .Rmd document that begins with an executive summary. I would like to include some inline R code to present a few of the key results up front; however, those results are calculated as part of the body later in the document.
Is there any way to present a result in the rendered document out of order/sequence with the actual calculation?
You could use chunk reuse in knitr (see http://yihui.name/knitr/demo/reference/). Here you would put your chunks to analyze first but not create the output, then output the summary, then the details. Here is some quick markdown knitr code to show this:
```{r chunk1, echo=FALSE, results='hide'}
x <- rnorm(1)
x
```
the value of x is `r x`.
```{r chunk2, ref.label='chunk1', echo=TRUE, results='markup', eval=2}
```
Note that the code will be evaluated twice unless you take steps to prevent this (the eval=2 in my example).
Another option would be to create 2 child documents, the first runs your main code and creates the output, the second creates the summary. Then in your parent document you include the summary first, then the detail part. I think that you will need to run knitr on these by hand so that you do it in the correct order, the automatic child document tools would probably run in the wrong order.