【问题标题】:Evaluate a variable so that it can appear in a code block for R markdown评估一个变量,使其可以出现在 R markdown 的代码块中
【发布时间】:2018-11-28 17:19:02
【问题描述】:

我正在使用 R Markdown 为统计课生成练习题,并且我喜欢包含一些随机性,以便同一问题可以有多个版本。学生们刚刚开始自己​​使用 R,我希望能够在答案 R 代码中显示正确的值。基本上我想实现这样的目标......

问题:

```{r, include=FALSE}
conf <- sample(c(0.9,0.95,0.99), 1)
```
What is the `r conf * 100`% confidence interval for the slope coefficient of your regression "reg"?

答案:

To get the correct answer run the following code
```{r}
confint(reg, level = magic_function(conf))
````

magic_function 是一些函数,它可以使生成的文档中的代码块看起来像这样......

confint(reg, level = 0.95)

【问题讨论】:

  • 我认为这可以使用knit_expand 来完成;请参阅knit_expand 小插图中的回归模型示例。

标签: r r-markdown knitr


【解决方案1】:

感谢 user2554330 让我走上了正确的道路。以下为我提供了想要的结果,尽管可能有更好的方法来做到这一点

答案:

To get the correct answer run the following code
```{r, include=FALSE}
code <- c("```{r}", knit::knit_expand(text = "confint(reg_result, level = {{conf}})", conf = conf), "```")
```
`r paste(knitr::knit(text = code), collapse = '\n')`

更新

看来如果你想拥有多个这样的代码块,你将需要使用 knit_child 而不是 knit,就像这样

答案:

To get the correct answer run the following code
```{r, include=FALSE}
code <- c("```{r}", knit::knit_expand(text = "confint(reg_result, level = {{conf}})", conf = conf), "```")
```
`r paste(knitr::knit_child(text = code), collapse = '\n')`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2012-06-09
    • 2011-01-15
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多