简体   繁体   English

有没有办法在Rmarkdown中执行条件降价块执行?

[英]Is there a way to have conditional markdown chunk execution in Rmarkdown?

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 . 我是一名教师,希望通过更改我创建的名为soln的文档参数,从同一个Rmarkdown文件中完成家庭作业和家庭作业解决方案指南。 When soln=FALSE the assignment document is generated, and when soln=TRUE the homework solution guide is generated. soln=FALSE ,生成分配文档,当soln=TRUE ,生成作业解决方案指南。 I can control R code chunk execution using the document parameter, but I would also like conditional inclusion of markdown text. 我可以使用document参数控制R代码块执行,但我还希望条件包含markdown文本。

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.
")
```

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. 我想要做的是用编写解决方案指南的人更换优雅和可读的内容来替换包含cat函数的块。 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. 我目前的方法对我来说足够了,但我不能让我的合作教师使用它,因为在cat函数中编写解决方案是如此不愉快。 (As a LaTeX user, it is also annoying to need double slashes for everything inside the math commands.) (作为一名LaTeX用户,在数学命令中需要双斜线也很烦人。)

Is there another way to do this? 还有另一种方法吗?

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 (ie, 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一样编写解决方案(例如,通常使用text, latex和R代码块的组合),而不是使用cat从R代码块中打印解决方案,并使用参数soln当您不希望在最终文档中包含解决方案时,请注释掉该部分。

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} ). 在下面的示例rmarkdown文档中,如果参数solnFALSE ,则行r if(!params$soln) {"\\\\begin{comment}"}插入\\begin{comment}以注释掉解决方案(使用匹配的代码)最后插入\\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.) (如果您喜欢这种格式,则不必为每个新段落或块输入双标签。如果您对一行执行此操作,则每次按Enter键时,新行将自动格式化使用双标签。或者,只需键入给定问题的所有文本和代码,然后在完成后,突出显示所有内容并键入tab两次。)

---
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}"}`

Also, instead of knitting the file above interactively, you can render both versions by running the render function in a separate R script. 此外,您可以通过在单独的R脚本中运行render函数来渲染这两个版本,而不是以交互方式编写上述文件。 For example, assuming the file above is called hw.Rmd , open a separate R script file and run the following: 例如,假设上面的文件名为hw.Rmd ,请打开一个单独的R脚本文件并运行以下命令:

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

Below is what Solutions.doc looks like. 以下是Solutions.doc样子。 Homework.doc is similar, except everything from the bold word Solution: onward is excluded: Homework.doc是类似的,除了大胆的单词Solution:向前的所有内容都被排除在外:

在此输入图像描述

I was able to build off this answer to make something that doesn't use a latex package (though I'm generating HTML slides, so that might be why this works). 我能够建立这个答案来制作一些不使用乳胶包的东西(虽然我正在生成HTML幻灯片,所以这可能就是为什么这样做了)。

Where you want the commenting out to begin, just add: `r if(params$soln) {"<!--"}` 你想要开始评论的地方,只需添加: `r if(params$soln) {"<!--"}`

And then add this to end the comment: `r if(params$soln) {"-->"}` 然后添加它来结束评论: `r if(params$soln) {"-->"}`

This didn't require me editing any of the thus-contained code blocks for conditional execution or anything else like that. 这不要求我编辑任何这样包含的条件执行代码块或其他任何类似的代码块。 Hope this helps someone! 希望这有助于某人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM