Programmatically insert header and plot in same code chunk with R markdown using results='asis'
You need to add some new lines after the plots and before the headers, using cat('\n')
:
```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
cat('\n#', Species, '\n')
p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
cat('\n')
}
Programmatically insert text, headers and lists with R markdown
You need to construct your wanted markdown in R and use that together with the argument results = 'asis'
in your chunk options. Hence, something like the following will do what you want:
```{r, results='asis'}
headers <- list("We","are","your","friends")
for (i in headers){
cat("#", i, "\n")
}
```
The for
-loop here will create the output
# We
# are
# your
# friends
which is used directly as input in the .md document.
Recommended way to initialize JS renderer in 'asis' R Markdown chunk
The answer to my question has been given by @cderv :
https://github.com/rstudio/rmarkdown/issues/1877#issuecomment-679864674
The results = 'asis' is now more documented in https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html#results-asis . It is aimed at generating raw mardown content from a R chunk. Anything must result in a text output, and implicitly that means no knitr magic really happens for any R object in those chunk, because knitr does no adjustment when knit_printing the content (as it is juts text)
I think I would not use result = 'asis' to cat() a complex R object like an htmlwidget. You found a workaround but you may encounter other issues.
As this answer has been liked by @yihui, it gives a hint that cat + asis
on htmlwidget
should be used at one's own risk.
However, I'll personnaly continue to use the workarounds mentioned in the question, because as long as it works I find it very practical.
Thanks @atusi & @cderv for their valuable input.
How to insert markdown in the middle of an knitr R code chunk?
You can use the function asis_output()
in knitr
to only output <br>
as is. So for instance, you can do this:
```{r}
plot(1:100, 1:100)
asis_output('<br>')
plot(1:100, 1:100)
```
This is better than using the results = 'asis'
option for the whole chunk because the two plots are not affected.
Note that this will also work for latex if you are knitting to pdf, but back slashes will have to be escaped. For example:
```{r}
plot(1:100, 1:100)
asis_output("\\\\newline")
plot(1:100, 1:100)
```
Inserting a page break within a code chunk in rmarkdown (converting to pdf)
See below a reduced and reproducible example. The answer and some general remarks:
- To dynamically create new pages or sections in a markdown document use
results='asis'
in the chunk options. - You have to add a linebreak (
\n
) after\\pagebreak
or else"ValueForV"
will be pasted directly after"\linebreak"
, which results in anUndefined control sequence
error. - Make sure that
\newpage
and\pagebreak
are in a separate line by using linebreaks\n
before. Escape
\newpage
and\pagebreak
(i.e.,\\newpage
,\\pagebreak
).---
title: "test"
output: pdf_document
---
```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
print(ggplot2::qplot(i, i+1))
cat("\n\n\\pagebreak\n")
writeLines("ValueForV")
}
```
R Markdown, output test results (htest) when chunk option results= asis
You can use formattable
like this
library(knitr)
library(formattable)
out <- prop.test(c(10,30), c(20,40))
cat("# Header \n")
cat(" \n## Straight output\n")
out # Only properly renders first line
cat(" \n## Print\n")
print(out) # Only properly renders first line
cat(" \n## Kable\n")
#kable(out) # Will fail: Error in as.data.frame.default(x) : cannot coerce class ""htest"" to a data.frame
kable(unlist(out)) # Renders everything but in an ugly way
cat(" \n## Pander\n")
df <- data.frame(value = unlist(out))
tdf <- as.data.frame(t(df))
formattable(tdf)
You can keep the columns you want, update the column names as all of these are in data frame
. A rough example of how it looks is here
Related Topics
How to Split an Igraph into Connected Subgraphs
Is There a Predict Function for Plm in R
How to Plot a Heat Map on a Spatial Map
How to Read the Source Code for an R Function
Fitting a Curve to Specific Data
Calculating Percentile of Dataset Column
Count the Number of Non-Zero Elements of Each Column
Plotting a "Sequence Logo" Using Ggplot2
How to Extend Letters Past 26 Characters E.G., Aa, Ab, Ac...
How to Merge Two Data Frames on Common Columns in R with Sum of Others
Annotate Values Above Bars (Ggplot Faceted)
How to Produce a Heatmap with Ggplot2
How to Read Huge CSV File into R by Row Condition
"Adding Missing Grouping Variables" Message in Dplyr in R
Using Geom_Rect for Time Series Shading in R