在R markdown中隐藏注释

7
在使用knitr / R markdown时,是否可以隐藏代码中的某些注释?例如:
---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document


---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```

当我编织时,我希望第一个评论消失,但仍保留第二个评论。

3
你可以编写一个自定义的输出勾子,根据任意标准删除行。 - Gregor Thomas
2个回答

12

这里是一个快速示例,展示如何修改钩子来改变 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 脚本中获取源代码,这种策略似乎不起作用。 - jsta

6

实际上,您可以通过将数字索引传递给块选项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文档以获取更多信息。


这个解决方案比被接受的答案更加优雅。虽然被接受的答案也相当聪明。 - DryLabRebel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接