【问题标题】:RMarkdown document - How to delay knitr evaluation of an inline code piece until later chunks have processed?RMarkdown 文档 - 如何延迟内联代码段的 knitr 评估,直到处理完以后的块?
【发布时间】:2018-05-27 15:26:04
【问题描述】:

我创建了一个 rmarkdown 报告,其中包含一堆代码块。我现在正在为其创建一个摘要首页,并希望包含一个内联计算,如

Blah blah blah summary stuff.... We found the mean to be `r mean(some_object_from_the_report)`. Blah blah blah more summary stuff.

作为 RMD 文件的开头,some_object_from_the_report 尚不存在。有没有办法告诉 knitr 推迟评估该代码 sn-p 直到后面的项目都被计算完?

感谢您的任何提示!

编辑:

建议在 knitr 选项中设置 echo=false。要么我做错了,要么对我的情况没有帮助。以下简短示例说明了这一点。

---
title: "Minimal test of delayed evaluation"
author: "sff"
date: "December 13, 2017"
output: html_document
---

```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = FALSE)
```

## Summary

Summary of blahblahblah. Also here's a mean from the report: `r mean(testobj)`.


## Report

```{r report_stuff}
testobj <- c(1, 2, 3)
```

Knitr 抛出未找到对象错误。我是否错误地执行了该建议,或者该建议没有达到我想要的效果?

【问题讨论】:

  • 感谢 Mako 的提示。下面的示例引发错误。一点帮助? --- 标题:“延迟评估的最小测试”作者:“sff”日期:“2017 年 12 月 13 日”输出:html_document --- {r setup, include=TRUE} knitr::opts_chunk$set(echo = FALSE) ## 总结 blahblahblah 的总结。这里还有一个来自报告的平均值:r mean(testobj)。 ## 报告{r report_stuff} testobj &lt;- c(1, 2, 3) 我错过了什么?
  • 我通常做的是创建一个包含要计算的字段的空列表,它们稍后在脚本期间填充并保存为 Rdata。下次我加载此列表时的第一件事。这需要运行脚本两次,但我在文章开头使用它来进行摘要。
  • @Cedric 所以这个想法是它第一次运行时输出中没有填充任何内容,但是计算被保存,所以它第二次运行时加载计算然后显示在输出中?
  • 是的,我会在下面举一个例子

标签: r knitr r-markdown


【解决方案1】:

这是一个简单的工作示例,您在摘要之前设置第一个块,如果您需要调整其他内容,例如\graphicspath{},可以在文档的最开头设置它。

如果包含列表的 Rdata 文件不存在,则在此块中创建一个列表。您需要使用文本中调用的值填充它。

当你第一次运行你得到的例子时

在第二次运行时你得到

请注意,这样可以避免运行冗长的计算并简单地保存结果。

\documentclass{article}    
\title{Testing how to save results for the abstract}
\author{}
\begin{document}
% this chunk comes just after begin{document}
<< init, echo=FALSE, eval=TRUE,results="hide" >>=
require(knitr)
summary_list_path <-paste0(getwd(),"/data/summary_list.Rdata")
if (!file.exists(summary_list_path)){
  summary_list<-list()
  summary_list[["A"]]<-list()
  summary_list[["B"]]<-list()
  summary_list[["A"]][["N"]]<-NA
  summary_list[["A"]][["p"]]<-NA
  summary_list[["B"]][["text"]]<-"extremely sad"
} else {
  load(summary_list_path)
}
@
\maketitle
\begin{abstract}
My population is \Sexpr{summary_list[["A"]][["N"]]} and the p value was \Sexpr{summary_list[["A"]][["p"]]} as a result I am \Sexpr{summary_list[["B"]][["text"]]}
\end{abstract}

<<chunk_1, echo=FALSE, eval=TRUE,results="hide" >>=
summary_list[["A"]][["N"]]<-20
summary_list[["A"]][["p"]]<-0.05
# save your list at the end of each chunk, that was you can also avoid 
# processing everyting.
save(summary_list,file=summary_list_path)
@

<<chunk_2, echo=FALSE, eval=TRUE,results="hide" >>=
summary_list[["B"]][["text"]]<-"happy"
save(summary_list,file=summary_list_path)
@

\end{document}

【讨论】:

  • 知道了。序列化作为延迟评估的替代方案。感谢您提供具体示例!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多