【问题标题】:Removing Comments from Printing in Knitr Output从 Knitr 输出中的打印中删除注释
【发布时间】:2017-06-23 17:37:18
【问题描述】:

我想知道是否有一种自动化的方法可以使 cmets 不会在输出中打印。现在,我使用以下代码来省略 cmets:

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

我想知道是否有一个现有的选项可以取出所有 cmets 或将 grep 传递给 echo 命令的能力,例如 echo=-function(x)grep(“^##”, x)。我知道一个特定的解决方案不起作用,但我想知道类似的事情是否可能?

此外,目前看来,如果我定义一个函数并注释该函数的各个方面,则整个函数都算作一个表达式,并且可以打印它(及其 cmets)或者它(及其所有 cmets)可以抑制,但似乎无法抑制函数内的 cmets。例如:

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

echo 语句中的 6 排除了所有内容

med.fun <- 
... 
}

这是唯一的行为还是可以抑制功能中的 cmets?

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    最接近的解决方案(可能不是您想要的)是设置块选项tidy = TRUE, tidy.opts = list(comment = FALSE),以便formatR 包将用于格式化您的代码并删除所有 cmets。如果要全局开启此功能,可以在文档的第一个代码块中设置knitr::opts_chunk$set(tidy = TRUE, tidy.opts = list(comment = FALSE))

    您可能不喜欢tidy = TRUE,但它比您提出的可能解决方案更可靠(如果您要处理 R 源代码,正则表达式并不健壮)。

    【讨论】:

    • 谢谢一辉!这真的很有帮助。我会试一试的。
    • 最后,一辉,你是对的,我不是特别喜欢tidy=TRUE。我分叉了 formatR 存储库并添加了一个传递参数,该参数仅删除以 ## 开头的行。这不是一个好的通用解决方案,但它适用于我的目的。
    • 整洁的评论对我不起作用。超级奇怪,消息,警告......没有任何作用。尽管在全局选项中将 all 设置为 false,但始终会打印注释,事实上,不仅仅是 cmets,甚至是部分代码。 (我通过source("sss.R")读取了一个外部函数)
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 2010-11-30
    • 2021-10-11
    • 2013-02-11
    • 2014-07-23
    • 2010-09-28
    • 2018-02-25
    • 2023-03-07
    相关资源
    最近更新 更多