You probably know that you can include a child document in a knitr document
(such as R Markdown) via the chunk option child. If you do not, you may see
Section 16.4 of the R Markdown
Cookbook.
You may also know that you can convert an R script to R Markdown via the
function knitr::spin(). Again, if you do not, you may read Section
3.3 of the book.
Then the question is, when you render an R Markdown document, can you spin a
child script inside that document? Tom asked this
question on Stack Overflow last
month, and the answer is “Yes.” There is a function knitr::spin_child()
designed exactly for this purpose. When you call this function inside an R code
chunk, it spins an R script to R Markdown, and includes the R Markdown document
as a child document of the main document. For example, if you have an R script
test.R:
#' # This is a child document
1 + 1
You can convert it to a child R Markdown document inside the main document:
---
title: The main document
---
```{r, echo=FALSE}
knitr::spin_child('test.R')
```
When you knit the main document above, you are essentially knitting this document below:
---
title: The main document
---
# This is a child document
```{r}
1 + 1
```
In conclusion, knitr::spin_child() enables you to write a part of your
report with an R script, if you do not want to write the whole report in an R
script.
Donate
As a freelancer (currently working as a contractor) and a dad of three kids, I truly appreciate your donation to support my writing and open-source software development! Your contribution helps me cope with financial uncertainty better, so I can spend more time on producing high-quality content and software. You can make a donation through methods below.
-
Venmo:
@yihui_xie, or Zelle:xie@yihui.name -
Paypal
-
If you have a Paypal account, you can follow the link https://paypal.me/YihuiXie or find me on Paypal via my email
xie@yihui.name. Please choose the payment type as “Family and Friends” (instead of “Goods and Services”) to avoid extra fees. -
If you don’t have Paypal, you may donate through this link via your debit or credit card. Paypal will charge a fee on my side.
-
-
Other ways:
WeChat Pay (微信支付:谢益辉) Alipay (支付宝:谢益辉) 

When sending money, please be sure to add a note “gift” or “donation” if possible, so it won’t be treated as my taxable income but a genuine gift. Needless to say, donation is completely voluntary and I appreciate any amount you can give.
Please feel free to email me if you prefer a different way to give. Thank you very much!
I’ll give back a significant portion of the donations to the open-source community and charities. For the record, I received about $30,000 in total (before tax) in 2024-25, and gave back about $15,000 (after tax).