Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

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

Is there another way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

In the sample rmarkdown document below, if the parameter soln is FALSE, then the line r if(!params$soln) {"\begin{comment}"} inserts egin{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{eta}_0$ is `r round(coef(fit1)[1], 2)`.

    The estimated X coefficient $hat{eta}_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. 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"))
}

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...