有没有办法使用RStudio删除R脚本中的所有注释?

时间:2014-05-13 11:53:21

标签: r comments rstudio

有没有办法使用RStudio删除R脚本中的所有注释?

我需要将文件缩小到可能的最小尺寸。但是,此文件的评论很多。

如果我是对的,支持REGEX的Rstudio中的搜索和替换功能可能对此有所帮助。

我感谢任何帮助。

1 个答案:

答案 0 :(得分:18)

我不会用正则表达式来完成这项任务。它可能有用,但仅限于简单的情况。请考虑以下/tmp/test.R脚本:

x <- 1 # a comment
y <- "#######"
z <- "# not a comment \" # not \"" # a # comment # here

f <- # a function
   function(n) {
for (i in seq_len(n))
print(i)} #...

如您所见,说明评论真正开始的位置有点复杂。

如果您不介意重新格式化代码(嗯,您声明您希望尽可能使用最小的代码),请尝试以下操作:

writeLines(as.character(parse("/tmp/test.R")), "/tmp/out.R")

将为/tmp/out.R提供:

x <- 1
y <- "#######"
z <- "# not a comment \" # not \""
f <- function(n) {
    for (i in seq_len(n)) print(i)
}

或者,使用formatR包中的函数:

library(formatR)
tidy_source(source="/tmp/test.R", keep.comment=FALSE)
## x <- 1
## y <- "#######"
## z <- "# not a comment \" # not \""
## f <- function(n) {
##     for (i in seq_len(n)) print(i)
## } 

BTW,tidy_source有一个blank参数,这可能是您感兴趣的。但我无法使用formatR 0.10 + R 3.0.2 ...

相关问题