Hide comments in R markdown

久未见 提交于 2020-01-29 21:24:06

问题


Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:

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


---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```

When kniting I would like the first comment to disapear, but keep the second one somehow.


回答1:


Here is a quick example of modifying the hook to change knitr behavior.

---
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

```

produces this




回答2:


In fact, you can choose to show any lines of R code by passing numeric indices to the chunk option echo, e.g.

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

```{r echo=4:7}

# Generate some data

rnorm(2)

## But keep this comment

```

See knitr documentation for more information.



来源:https://stackoverflow.com/questions/44399048/hide-comments-in-r-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!