MYaseen208
MYaseen208

Reputation: 23898

Excluding some patterned code in read_chunk knitr function in R

I'm using read_chunk function to read R code from external file. Sometimes I add comments for myself but I want to exclude those comments in my final document. I wonder how can the following pattern

###################################################
### code chunk number 1:
###################################################

can be excluded in read_chunk function.

###################################################
### code chunk number 1:
###################################################
## ---- Code1 ----
Some Code


###################################################
### code chunk number 2:
###################################################
## ---- Code2 ----
Some Code

###################################################
### code chunk number 3:
###################################################
## ---- Code3 ----
Some Code

###################################################
### The End
###################################################

Thanks in advance for your help.

Upvotes: 1

Views: 167

Answers (1)

baptiste
baptiste

Reputation: 77096

I guess you can filter out the lines you don't want,

code <- "
###################################################
### code chunk number 1:
###################################################
## ---- Code1 ----
ls()


###################################################
### code chunk number 2:
###################################################
## ---- Code2 ----
ls()

###################################################
### code chunk number 3:
###################################################
## ---- Code3 ----
ls()

###################################################
### The End
###################################################
"

codelines <- readLines(textConnection(code))
# if the code is in file 'mycode.txt'
# codelines <- readLines('mycode.txt')
codelines <- codelines[!codelines == ""] # empty lines
keep <- !grepl("###", x=codelines) # comment lines
read_chunk(lines=paste(codelines[keep]))
knitr:::knit_code$get()  
knitr:::knit_code$restore()

Upvotes: 2

Related Questions