有没有办法在Rmarkdown中有条件地执行Markdown块? [英] Is there a way to have conditional markdown chunk execution in Rmarkdown?

查看:118
本文介绍了有没有办法在Rmarkdown中有条件地执行Markdown块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一位指导老师,希望通过更改我创建的称为soln的文档参数,从同一Rmarkdown文件进行作业分配和作业解决方案指南.在soln=FALSE时生成工作分配文档,在soln=TRUE时生成作业解决方案指南.我可以使用document参数控制R代码块的执行,但我也希望有条件地包含降价文字.

I am an instructor looking to make a homework assignment and homework solution guide from the same Rmarkdown file by changing a document parameter I created called soln. When soln=FALSE the assignment document is generated, and when soln=TRUE the homework solution guide is generated. I can control R code chunk execution using the document parameter, but I would also like conditional inclusion of markdown text.

我当前的解决方法很丑:

My current workaround is ugly:

---
title: "Homework"
output: word_document
params:
  soln: TRUE
---
Fit the linear regression model $Y \sim X$ with the following data.     
Interpret the coefficient estimates.
```{r promptchunk, include = TRUE, echo = TRUE}
# R code I want to show in the question prompt goes here
# This executes in both assignment and solution versions
set.seed(123)
X <- c(1, 1, 0, 0)
Y <- rnorm(4)
```
```{r, include = params$soln, echo = FALSE, results = "asis"}
cat("
**ANSWER**
")
```
```{r, echo = params$soln, include = params$soln, eval = params$soln}
# R code corresponding to the solution
fit1 <- lm(Y ~ X)
summary(fit1)
```
```{r, include = params$soln, echo = FALSE, eval = params$soln, results = "asis"}
cat("
The interpretation of the intercept is.... 
Our estimate $\\hat{\\beta}_0$ is ",coef(fit1)[1],".
The estimated X coefficient $\\hat{\\beta}_1$ is ",coef(fit1)[2]," 
This can be interpreted as....

You can imagine that for more difficult questions, this section could be quite long.
")
```

我想做的是用编写解决方案指南的人更优雅,更易读的东西替换包含cat函数的块.我目前的方法对我来说已经足够有效,但是我不能要求我的共同讲师使用这种方法,因为在cat函数内部编写解决方案太不愉快了. (作为LaTeX用户,在数学命令中的所有内容都需要双斜杠也很烦人.)

What I would like to do is to replace the chunks containing cat functions with something more elegant and readable for the person writing the solutions guide. My current approach works enough for me, but it is not something that I could ask my co-instructors to use because it is so unpleasant to write the solutions inside of the cat function. (As a LaTeX user, it is also annoying to need double slashes for everything inside the math commands.)

还有另一种方法吗?

推荐答案

您可以像通常在rmarkdown中那样编写解决方案,而不必使用cat从R代码块中打印解决方案. (通常是文本,latex和R代码块的组合),并且当您不想在最终文档中包含解决方案时,请使用参数soln将该部分注释掉.

Instead of using cat to print the solution from within an R code chunk, you could write the solution as you usually would in rmarkdown (i.e., with the usual combination of text, latex, and R code chunks), and use the parameter soln to comment out that section when you don't want to include the solution in the final document.

在下面的示例rmarkdown文档中,如果参数solnFALSE,则行r if(!params$soln) {"\\begin{comment}"}插入\begin{comment}以注释掉解决方案(末尾带有匹配代码以插入\end{comment} ).我还用两个选项卡对所有内容进行了缩进,以便问题编号以悬挂式缩进格式显示. (如果您喜欢这种格式,则不必为每个新段落或大块键入双重选项卡.如果您为一行输入此选项,则随后每按一次Enter键,新行将自动可以使用双标签进行格式化.或者,只需输入您给定问题的所有文本和代码,然后在完成后将所有内容突出显示并输入tab两次.)

In the sample rmarkdown document below, if the parameter soln is FALSE, then the line r if(!params$soln) {"\\begin{comment}"} inserts \begin{comment} to comment out the solution (with matching code at the end to insert \end{comment}). I've also indented everything with two tabs, so that the question numbers are formatted with a hanging-indent. (If you like this format, you don't have to type the double-tab for each new paragraph or chunk. If you do this for one line, then each subsequent time you press the Enter key, the new line will automatically be formatted with the double-tab. Or, just type in all your text and code for a given question, then when you're done, highlight all of it and type tab twice.)

---
title: "Homework"
output: word_document
header-includes:
  - \usepackage{comment}
params:
  soln: TRUE
---

1. Fit the linear regression model $Y \sim X$ with the following data. Interpret the coefficient estimates.

    ```{r promptchunk, echo = TRUE}
    set.seed(123)
    X <- c(1, 1, 0, 0)
    Y <- rnorm(4)
    ```

`r if(!params$soln) {"\\begin{comment}"}`

    **Solution:**

    Run the following R code to fit the linear regression model:
    ```{r, include = params$soln, echo = TRUE, results = "asis"}
    fit1 = lm(Y ~ X)
    ```

    To see a summary of the regression results, run the following code and review the output: 

    ```{r, include = params$soln, echo=TRUE}
    summary(fit1)
    ```
    The interpretation of the intercept is.... 

    Our estimate $\hat{\beta}_0$ is `r round(coef(fit1)[1], 2)`.

    The estimated X coefficient $\hat{\beta}_1$ is `r round(coef(fit1)[2], 2)`. 

    This can be interpreted as....

`r if(!params$soln) {"\\end{comment}"}`

此外,您可以通过在单独的R脚本中运行render函数来呈现两个版本,而不是交互式地编织上述文件.例如,假设上面的文件名为hw.Rmd,请打开一个单独的R脚本文件并运行以下命令:

Also, instead of knitting the file above interactively, you can render both versions by running the render function in a separate R script. For example, assuming the file above is called hw.Rmd, open a separate R script file and run the following:

for (i in c(TRUE, FALSE)) {
  rmarkdown::render("hw.Rmd", 
                    params = list(soln = i),
                    output_file=ifelse(i, "Solutions.doc", "Homework.doc"))
}

下面是Solutions.doc的外观. Homework.doc与之类似,但不包括粗体字 Solution: 之后的所有内容:

Below is what Solutions.doc looks like. Homework.doc is similar, except everything from the bold word Solution: onward is excluded:

这篇关于有没有办法在Rmarkdown中有条件地执行Markdown块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆