2017-06-06 93 views
1

當使用knitr/R markdown進行鍼織時,可以在代碼中隱藏一些註釋嗎?例如:在R markdown中隱藏評論

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


--- 

```{r} 

# Generate some data 

rnorm(2) 

## But keep this comment 

``` 

編織時,我想第一個評論放棄,但保持第二個莫名其妙。

+3

你可以編寫一個自定義的[輸出鉤子](https://yihui.name/knitr/hooks/),根據你想要的任何標準刪除線條。 – Gregor

回答

6

下面是一個修改掛鉤以改變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 

``` 

產生此enter image description here

+0

如果使用'knitr :: read_chunk'從單獨的R腳本中獲取這個策略似乎不起作用 – jsta

1

事實上,可以選擇通過傳遞數字索引到塊選項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