我是一位教師,希望通過更改我創建的名爲soln
的文檔參數來從同一個Rmarkdown文件中完成作業分配和作業解決方案指南。當soln=FALSE
生成作業文檔時,並且soln=TRUE
生成作業解決方案指南。我可以使用文檔參數控制R代碼塊的執行,但是我還希望有條件地包含減價文本。有沒有辦法在Rmarkdown中有條件降價組塊執行?
我目前的解決方法是醜陋:
---
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用戶,數學命令中的所有內容都需要雙斜槓也很煩人。)
是否有另一種方法可以做到這一點?
你是說,你的當前版本的「作品」,但你會喜歡的東西更容易理解和維護?另外,你可以添加一個你會問的真實問題的例子,以及解決方案,這樣我們就可以瞭解R代碼中需要做什麼以及什麼是文本? – eipi10
@ eip10,我更新了我的問題。目前的版本確實有效,但是有條件的塊執行需要被封裝在「cat」函數中,與典型的Rmarkdown相比,它更直觀,更難讀寫。我試圖讓一般的輔導員有可重複性和Rmarkdown,但是我不能讓他們看到這個爛攤子,並期待買入。我_think_我正在尋找一種方法來繞過R作爲處理某些文本塊的引擎。 – thatssobayesic
編織時是否有條件地包含文件?在代碼塊中執行所有文本似乎很奇怪。也許看看書和/或筆記本。 – Elin