Related
I have the followin markdown:
---
title: "My report"
output: html_document
---
```{r setup, include=FALSE}
library(DT)
my_func <- function(x) {
#DT::datatable(x)
print(DT::datatable(x))
nrow(x)
}
```
```{r}
x <- my_func(mtcars)
print(x)
```
I want to display a DT from inside the function, but this function performs some calculations that I'm interested in the output of. So far it doesn't display the table. How can I force markdown to generate a table without returning it?
What about something like this:
---
title: "My report"
output: html_document
---
```{r setup, include=FALSE}
library(DT)
my_func <- function(x) {
res <- list(dt = DT::datatable(x),
nr = nrow(x))
class(res) <- "myfun"
invisible(res)
}
```
```{r}
x <- my_func(mtcars)
x$nr
```
```{r}
x$dt
```
Is it possible to move the caption above my figure when knitting to HTML in RMarkdown? It seems that it is possible in PDF, ie when knitting to PDF, but I can't figure out how to replicate this for HTML. I am using bookdown to number figures.
When I run something like this:
```{r fig.cap= "caption"}
df <- data.frame(letter = letters[1:5], value = 1)
ggplot(df, aes(as(factor(1), value, fill = letters))) +
geom_bar(stat = "identity")
```
the caption is displayed at the bottom of the figure, but I would like to display it above the figure.
For HTML output, you may set the chunk option fig.topcaption = TRUE to place captions above figures. Below is a minimal example (it works for both html_document and bookdown's HTML output formats):
---
title: "Reprex"
output:
html_document: null
bookdown::html_document2: null
---
```{r, fig.cap='A caption.', fig.topcaption=TRUE}
plot(cars)
```
You can do that, but if you set echo = TRUE, the caption will appear above the code...
---
title: "Untitled"
author: "Stéphane Laurent"
date: "29 février 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::knit_hooks$set(htmlcap = function(before, options, envir) {
if(before) {
paste('<p class="caption">', options$htmlcap, "</p>",sep="")
}
})
```
```{r, echo = FALSE, htmlcap="Hello Dolly"}
library(ggplot2)
ggplot(diamonds,aes(price,carat)) + geom_point()
```
This is not a successful answer, but code output shows that the choice of a bookdown format, that would otherwise number the figure, is suppressed by inclusion of the solution proposed by Stéphane, or, as below, solution from the link suggested by dyrland.
---
title: "Untitled"
author: "Internet"
date: "29 février 2020"
output:
bookdown::html_document2
---
```{r setup2}
#https://stackoverflow.com/a/26743812/4927395
library(knitr)
knit_hooks$set(plot = function(x, options) {
paste('<figure><figcaption>', options$fig.cap, '</figcaption><img src="',
opts_knit$get('base.url'), paste(x, collapse = '.'),
'"></figure>',
sep = '')
}) #comment out to restore numbering
library(ggplot2)
```
```{r, echo = TRUE, fig.cap="Hello Dolly"}
ggplot(diamonds,aes(price,carat)) + geom_point()
```
Can a solution include both the numbering and the caption at the top?
N.B Author of the original question did mention bookdown, but did not provide a full working example to demonstrate this. Happy to edit original question if other think that would be more useful.
EDIT
Yihui has shown in his answer that there is an easy option with fig.topcaption=TRUE - Thanks! Unfortunately that caption, though it retains correct numbering, is still pushed to the bottom (in the case of plotly figures). Example below:
---
title: "Untitled"
author: "Internet"
date: "29 février 2020"
output:
bookdown::html_document2
---
```{r setup, message=FALSE, echo=FALSE}
library(knitr)
library(ggplot2)
library(plotly)
```
Here is a ggplot object with caption at the top as desired.
```{r, fig.cap="Hello ggplot", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
ggplot(diamonds,aes(price,carat)) + geom_point()
```
Here is the previous ggplot converted to a plotly object with caption reverting to the bottom.
```{r, fig.cap="Hello plotly", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
my_ggplot <- ggplot(diamonds,aes(price,carat)) + geom_point()
ggplotly(my_ggplot)
```
Caption reverts to bottom even if plotly object is not created from ggplot object
```{r, fig.cap="Hello plotly2", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
plot_ly(
x=c(1,2,3),
y=c(5,6,7),
type='scatter',
mode='lines')
```
EDIT 2
Plotly caption location issue solved with css here
Hardcoding a function is function is never my preferred option, but it works (Create another function for Tables.) (Source code here: R Markdown HTML Number Figures)
Now, to figure out how to reference these...
---
title: "Untitled"
author: "Internet"
date: "29 fevrier 2020"
output:
bookdown::html_document2
---
```{r setup2}
#https://stackoverflow.com/a/26743812/4927395
library(knitr)
library(ggplot2)
capFigNo <- 1
capFig <- function(x){
x <- paste0("Figure ",capFigNo,": ",x)
capFigNo <<- capFigNo + 1
x
}
knit_hooks$set(plot = function(x, options) {
paste('<figure><figcaption>',
options$fig.cap,
'</figcaption><img src="',
opts_knit$get('base.url'),
paste(x, collapse = '.'),
'"></figure>',
sep = '')
}) #comment out to restore numbering
```
```{r echo = TRUE, fig.cap=capFig("Hello Dolly")}
#the trick is to wrap your caption in your number prefixing function.
ggplot(diamonds,aes(price,carat)) + geom_point()
```
```{r echo = TRUE, fig.cap=capFig("Hello Dolly2")}
ggplot(diamonds,aes(price,carat)) + geom_point()
```
I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.
For example
---
title: "test"
output: pdf_document
---
```{r, results='asis'}
for (i in 1:10) {
cat("\\section{Part:", i, "}")
summary(X)
$\alpha = `r X[1,i]`$
}
```
pretty much does the trick, but here there are still two problems:
the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible
Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?
I am very thankful for every kind of advice
You can do what you are after inline without relying as much on code blocks.
As a minimal example.
---
title: "test"
output: pdf_document
---
```{r sect1_prep, include=FALSE}
i <- 1
```
\section{`r paste0("Part: ", i)`}
```{r sect1_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
```{r sect2_prep, include=FALSE}
i <- i + 1
```
\section{`r paste0("Part: ", i)`}
```{r sect2_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
Produces...
If you really want to have a section factory, you could consider pander.
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
empty <- lapply(1:10, function(x) {
pandoc.header(paste0("Part: ", x), level = 2)
pander(summary(mtcars[, x]))
pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))
})
```
which produces...
remove summary table format example
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
content <- lapply(1:10, function(x) {
head <- pandoc.header.return(paste0("Part: ", x), level = 2)
body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))
return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))
})
writeLines(unlist(content), sep = "\n\n")
```
The following code is a very simplified MRE for an issue I'm experiencing. I'm trying to avoid R template packages, such as brew, and only use knit_expand() to achieve my goals. The issue is twofold:
generated chunks don't get parsed (this is not happening in my real code, but happens in MRE)
instead of LaTeX \includegraphics, knitr (or rmarkdown, or pandoc) generates RMarkdown syntax for inserting figures (![]).
In regard to the former, I have a feeling that it might be related to my incorrect use of get() or its argument. Your advice would be very much appreciated. The MRE follows ('.Rmd' document):
---
title: "MRE: a dynamic chunk issue"
author: "Aleksandr Blekh"
output:
pdf_document:
fig_caption: yes
keep_tex: yes
highlight: NULL
---
```{r, echo=FALSE, include=FALSE}
library(knitr)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE, message=FALSE, echo=FALSE, tidy=FALSE)
```
```{r Preparation, results='hide'}
g1 <- plot(cars)
g2 <- plot(iris$Sepal.Length)
myPlots <- list(g1, g2)
bcRefStr <- list("objType" = "fig",
"objs" = c("g1", "g2"),
"str" = "Plots \\ref{fig:g1} and \\ref{fig:g2}")
```
```{r DynamicChunk, include=FALSE}
chunkName <- "{{name}}"
chunkHeader <- paste0("```{r ", chunkName, ", ")
chunkOptions <- "include=TRUE, results='asis', fig.height=4, fig.width=4, fig.cap='{{name}}'"
chunkHeaderFull <- paste0(chunkHeader, chunkOptions, "}")
chunkBody <- "print(get('{{name}}'))"
latexFigEnvBegin <- "cat('\\\\begin{figure}')"
latexFigEnvEnd <- "cat('\\\\end{figure}')"
latexFigCenter <- "cat('\\\\centering')"
latexObjLabel <- paste0("cat('\\\\caption{\\\\ ", "{{name}}\\\\label{", bcRefStr$objType, ":{{name}}", "}}')")
chunkText <- c(chunkHeaderFull,
latexFigEnvBegin, latexFigCenter,
chunkBody,
latexObjLabel, latexFigEnvEnd,
"```", "\n")
figReportParts <- lapply(bcRefStr$objs, function (x) knit_expand(text = chunkText, name = x))
```
`r knit(text = unlist(figReportParts))`
Finally, I've figured out what was causing the issue. The first part was easy. Due to suggested simplification, I've switched from ggplot2 to standard R graphics functions. The problem is that it appears that plot() doesn't return a value/object, so that's why NULLs has been seen in the output, instead of plots.
The second part was a bit more tricky, but an answer to a related question (https://stackoverflow.com/a/24087398/2872891) clarified the situation. Based on that information, I was able modify my MRE correspondingly and the resulting document appears with correct content (same applies to the generated LaTeX source, which seems to be ready for cross-referencing).
I'm thinking about converting this code into a more generic function for reuse across my project, if time will permit [shouldn't take long] (#Yihui, could this be useful for knitr project?). Thanks to everyone who took time to analyze, help or just read this question. I think that knitr's documentation should be more clear on issues, related to producing PDF documents from RMarkdown source. My solution for the MRE follows.
---
title: "MRE: a dynamic chunk issue"
author: "Aleksandr Blekh"
output:
pdf_document:
fig_caption: yes
keep_tex: yes
highlight: NULL
---
```{r, echo=FALSE, include=FALSE}
library(knitr)
library(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE, message=FALSE, echo=FALSE, tidy=FALSE)
```
```{r Preparation, results='hide'}
library(ggplot2)
g1 <- qplot(mpg, wt, data=mtcars)
g2 <- qplot(mpg, hp, data=mtcars)
myPlots <- list(g1, g2)
bcRefStr <- list("objType" = "fig",
"objs" = c("g1", "g2"),
"str" = "Plots \\ref{fig:g1} and \\ref{fig:g2}")
```
```{r DynamicChunk, include=FALSE}
latexObjLabel <- paste0("{{name}}\\\\label{", bcRefStr$objType, ":{{name}}", "}")
chunkName <- "{{name}}"
chunkHeader <- paste0("```{r ", chunkName, ", ")
chunkOptions <- paste0("include=TRUE, results='asis', fig.height=4, fig.width=4, fig.cap='", latexObjLabel, "'")
chunkHeaderFull <- paste0(chunkHeader, chunkOptions, "}")
chunkBody <- "print(get('{{name}}'))"
chunkText <- c(chunkHeaderFull,
chunkBody,
"```", "\n")
figReportParts <- lapply(bcRefStr$objs, function (x) knit_expand(text = chunkText, name = x))
```
`r knit(text = unlist(figReportParts))`
I want to set the chunk option "eval" based on a list of chunk names. Is there a function to get the chunk name in knitr, e.g. chunk_name?
This is my minimum example with fake function name "chunk_name".
---
output: html_document
---
```{r setup}
eval_chunks <- c('chunk1')
```
```{r chunk1, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
```{r chunk2, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
Thanks for any suggestions. Please let me know if my question is not clear.
Knitr provided labels inside a chunk since 2012 (need more Google, https://github.com/yihui/knitr/issues/73).
This is my sample Rmd file:
---
output: html_document
---
```{r setup}
library(knitr)
eval_chunks <- c('chunk1', 'chunk3')
```
```{r chunk1, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk2, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk3, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
I think this solution is imperfect because it requires a bit of care in making sure the correct chunks are evaluated, but it gets around the problem that chunk options are evaluated before hooks are called. In short, it doesn't use a hook, but instead uses the fact that chunk options can be R expressions. In this case, a function e() is used that relies on a global counter variable to dictate whether a particular chunk should be evaluated. Because chunks are evaluated in order, this works. In the below example, chunk1 and chunk3 are evaluated, but the others are not.
---
output: html_document
---
```{r setup}
library("knitr")
.i <- 2 # `setup` is the first chunk, so start at 2
.x <- all_labels() %in% c("chunk1", "chunk3")
e <- function(){
d <- .x[.i]
.i <<- .i + 1
d
}
```
```{r chunk1, eval=e()}
x <- 1
x
```
```{r chunk2, eval=e()}
x <- 2
x
```
```{r chunk3, eval=e()}
x <- 3
x
```
```{r chunk4, eval=e()}
x <- 4
x
```