Comments (11)
Not sure from which data Distance
or Speed
comes from to reproduce, but several comments.
Instead of for
loop with cat()
, you should consider going all knit_child
way, and generate the all md
content you want to iterate on as a child using knit_expand()
or directly text content in knit_child
with inline R code
See the others recipes in the cookbook about that:
- https://bookdown.org/yihui/rmarkdown-cookbook/knit-expand.html
- https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html
This will allow you to add your plots inside a chunk, with right conditional. That way each plot will be differently handle and correctly by knitr.
You can't just cat()
plot, so having it process by knit_child()
could be rather important.
I let you try a version. I can show you if you share with the data.
from knitr.
@cderv Sorry because the minrep was not complete. Now I updated including data source.
from knitr.
Can you format correctly please ? https://yihui.org/issue/#please-format-your-issue-correctly
Also you can try with what I shared. I believe it will make your intention works
from knitr.
@cderv Yes. I updated the format again. Sorry for the inconvenience.
Going to matter, I do not understand how should I do. https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html with knit_child
is what I am already using. How should be the exemple adapted to your proposal?
Thanks!
from knitr.
Several examples
directly creating text to knit as a child
This is close to what you are doing, but instead, you are just generating the child content as a whole as a vector. Not using cat()
and letting knit_child()
to all the printing when knitting
---
title: test
output:
html_document:
keep_md: true
---
```{r setup, echo=TRUE, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results = 'asis',
fig.height = 6, fig.width = 10,
eval = TRUE, message = FALSE, warning = FALSE)
library(knitr)
Speed <- cars$speed
Distance <- cars$dist
```
```{r echo = FALSE, results='asis'}
content <- c()
for (i in 1:1) {
for (j in 1:2) {
content <- c(
content,
sprintf("j = %d", j),
"\n\n",
"```{r, echo = FALSE}",
if (j == 1) 'plot(Speed, Distance, panel.first = grid(8, 8), pch = 0, cex = 1.2, col = "blue")',
if (j == 2) 'plot(Speed, Distance, panel.first = lines(stats::lowess(Speed, Distance), lty = "dashed"), pch = 0, cex = 1.2, col = "blue")',
"```",
"\n\n",
"```{r, echo = FALSE}",
"kable(mtcars)",
"```",
"\n\n"
)
}
content <- c(
content,
c(
'```{r}',
'plot(pressure)',
"```",
"\n\n"
)
)
}
knitr::knit_child(text = content, envir = environment(), quiet = TRUE) |> cat(sep = "\n")
```
Using an external child document
You write the content to use in knit_child
in another doc, using inline R code and code chunk as you would in a generic doc, but to access variable from your main document
test.Rmd
---
title: test
output:
html_document:
keep_md: true
---
```{r setup, echo=TRUE, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results = 'asis',
fig.height = 6, fig.width = 10,
eval = TRUE, message = FALSE, warning = FALSE)
library(knitr)
Speed <- cars$speed
Distance <- cars$dist
```
```{r echo = FALSE, results='asis'}
res <- lapply(1:2, function(j) {
knit_child("_child.Rmd", envir = environment(), quiet = TRUE)
})
cat(unlist(res), sep = '\n')
```
```{r}
kable(mtcars)
```
```{r}
plot(pressure)
```
_child.Rmd
j = `r j`
```{r, eval = j == 1, echo = j == 1}
plot(Speed, Distance, panel.first = grid(8, 8), pch = 0, cex = 1.2, col = "blue")
```
```{r, eval = j == 2, echo = j == 2}
plot(Speed, Distance, panel.first = lines(stats::lowess(Speed, Distance), lty = "dashed"), pch = 0, cex = 1.2, col = "blue")
```
Same but using knit_expand()
or another template function to fill a child file
You write the content to knit_child
in an external file, using templating expansion to fill the value you need to be variable
test.Rmd
---
title: test
output:
html_document:
keep_md: true
---
```{r setup, echo=TRUE, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results = 'asis',
fig.height = 6, fig.width = 10,
eval = TRUE, message = FALSE, warning = FALSE)
library(knitr)
Speed <- cars$speed
Distance <- cars$dist
```
```{r echo = FALSE, results='asis'}
res <- lapply(1:2, function(j) {
knit_child("_child.Rmd", envir = environment(), quiet = TRUE)
})
cat(unlist(res), sep = '\n')
```
```{r}
kable(mtcars)
```
```{r}
plot(pressure)
```
Details
j = {{j}}
```{r, eval = {{ j == 1 }}, echo = {{ j == 1 }} }
plot(Speed, Distance, panel.first = grid(8, 8), pch = 0, cex = 1.2, col = "blue")
```
```{r, eval = {{ j == 2 }}, echo = {{ j == 2 }} }
plot(Speed, Distance, panel.first = lines(stats::lowess(Speed, Distance), lty = "dashed"), pch = 0, cex = 1.2, col = "blue")
```
Other templating tools like brew, whisker , even glue could be used with same purpose.
Hope it helps see what you can do to avoid cat()
and print()
mixing text and R object output
from knitr.
@cderv Wow! That is impressive.
Finally I could get what I wanted using an external child document and splitting code in distinct chunks there.
Thank you for your help.
I keep the issue open as I believe the behaviour reported is yet a bug. Feel free to close it if that behaviour is expected (and already documented?)
from knitr.
It is tricky as issue because you are missing
cat()
of raw markdow, and print()
of plots and kable()
, without any results = "asis"
set is quite specific, and does not seem correct usage. So I don't know if this is a bug or not.
It would require to minimized the example I believe.
@yihui do you think there is something to look into ?
from knitr.
Actually results = 'asis'
is specified by default through knitr::opts_chunk$set
, and I only use cat
for knit_child
and the separator cat('\n\n<!-- -->\n\n')
, which I would not use if they were unneeded.
from knitr.
Actually results = 'asis' is specified by default through knitr::opts_chunk$set,
Oh that is why. Ok thanks for clarification !
from knitr.
A smaller reprex with knit_child()
---
title: test
output:
html_document:
keep_md: true
---
```{r pressure, results='asis'}
plot(cars$speed, cars$dist, panel.first = grid(8, 8), pch = 0, cex = 1.2, col = "blue")
knitr::kable(head(cars))
knitr::knit_child(text = c(
'```{r}',
'plot(pressure)',
'```'
), envir = environment(), quiet = TRUE) |> cat(sep="\n")
```
Which do no happen without
---
title: test
output:
html_document:
keep_md: true
---
```{r pressure, results='asis'}
plot(cars$speed, cars$dist, panel.first = grid(8, 8), pch = 0, cex = 1.2, col = "blue")
knitr::kable(head(cars))
plot(pressure)
```
So probably something to look into 🤔
from knitr.
This does seem to be a complicated bug. I haven't figured out the reason after some investigation. Sorry.
from knitr.
Related Issues (20)
- [spin] Better support for `roxygen2` style comments
- Algorithmic complexity of dep_auto HOT 1
- default graphics device to more performant ragg HOT 3
- knitr cache does not recognize magrittr assignment pipe HOT 2
- WISH: Make it possible to call globalCallingHandlers() in a chunk
- Animation not rendering in powerpoint HOT 1
- Error(s) in re-building vignettes: HOT 2
- table output for typst HOT 8
- html/css rendering to PDF HOT 3
- export some pandoc syntax helper HOT 2
- Make `asis_output` works for Quarto the same as `results: asis`
- output hooks and current chunk options
- write_bib producing NULL in knitr 1.45 HOT 5
- feature request: tweak non-escaped ampersand HOT 7
- fig.ncol not working with Latex HOT 2
- `* 2.` does not produce <li>2.</li> HOT 1
- catch error=TRUE chunks produced by hook_purl() HOT 5
- Problem caching instances of torch modules and datasets
- write_bib() includes multiple URLs HOT 3
- autodep regression by #2321 HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from knitr.