Reputation: 21937
I was wondering if there is an automated way to make it so comments don’t print in the output. Right now, I’m using the following to omit comments:
<<relimpsum, echo=-c(1,3,4,5)>>=
## load relimp package
library(relimp)
## calculate relative improtance of
## sector (coefs 3:11) and
## nation (coefs 12:14)
relimp(mod1, set1=3:11, set2=12:14)
@
I was wondering if there is an existing option that would take out all comments or the ability to pass grep to the echo command, e.g., echo=-function(x)grep(“^##”, x). I know for a fact that particular solution doesn’t work, but I was wondering if something similar might be possible?
Also, it appears that currently if I define a function and comment aspects of the function, that the entire function counts as a single expression and either it (and its comments) can be printed or it (and all of its comments) can be suppressed, but it appears as though it is not possible to suppress the comments within a function. For example:
<<withboot, echo=-c(1,3,5,6)>>=
## Bootstrapping the median with the boot package
library(boot)
## set random number generator
set.seed(123)
## define function that we will bootstrap
med.fun <- function(x, inds){
## assigns .inds to the global environment to
## ensure that the appropriate obs numbers get
## used in the resampling
assign(".inds", inds, envir=.GlobalEnv)
## calculate the median for the resampled x values
med <- median(x[.inds])
## remove the .inds from the global environment
remove(".inds", envir=.GlobalEnv)
## return the bootstrapped median
med
}
## use the boot function to botstrap the median
boot.med <- boot(x, med.fun, R=1000)
boot.ci(boot.med)
@
The 6 in the echo statement excludes everything from
med.fun <-
...
}
Is this the only behaviour or can the in-function comments also be suppressed?
Upvotes: 4
Views: 3819
Reputation: 30114
The closest solution (may not be exactly what you want) is to set the chunk options tidy = TRUE, tidy.opts = list(comment = FALSE)
so that the formatR package will be used to format your code and remove all comments. If you want to turn on this feature globally, you may set knitr::opts_chunk$set(tidy = TRUE, tidy.opts = list(comment = FALSE))
in the first code chunk of your document.
You may not like tidy = TRUE
, but it is more reliable than the possible solution you proposed (regular expressions are not robust if you want to process R source code).
Upvotes: 2