【问题标题】:Hide comments in R markdown在 R markdown 中隐藏评论
【发布时间】:2017-06-06 20:14:32
【问题描述】:

使用 knitr / R markdown 编织时是否可以在代码中隐藏一些 cmets?示例:

---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document


---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```

编织时,我希望第一个评论消失,但以某种方式保留第二个评论。

【问题讨论】:

  • 您可以编写一个自定义的output hook,根据您想要的任何标准删除行。

标签: r latex markdown knitr


【解决方案1】:

这是一个修改钩子以改变 knitr 行为的快速示例。

---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---

```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
    x <- x[!grepl("^#\\s+", x)]
    paste0("```r\n",
          paste0(x, collapse="\n"),
          "\n```")
}
knitr::knit_hooks$set(source = hook_in)
```

```{r}

# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents

rnorm(2)

## But keep this comment
## But lines that starts with `## ` will be kept

```

产生这个

【讨论】:

  • 如果使用knitr::read_chunk从单独的 R 脚本进行采购,此策略似乎不起作用
【解决方案2】:

实际上,您可以通过将数字索引传递给块选项echo 来选择显示任何 R 代码行,例如

---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document
---

```{r echo=4:7}

# Generate some data

rnorm(2)

## But keep this comment

```

更多信息请参见knitr documentation

【讨论】:

  • 这是一个比公认的答案更优雅的解决方案。虽然接受的答案很聪明。
猜你喜欢
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 2015-08-01
  • 1970-01-01
相关资源
最近更新 更多