Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to delete all comments in a R script using RStudio?

Is there a way to delete all comments in a R script using RStudio?

I need to shrink a file to the smallest size possible. However, this file is heavily commented.

If I am right the search and replace function in Rstudio supporting REGEX might be helpful with this endeavor.

I appreciate any help.

like image 832
majom Avatar asked May 13 '14 11:05

majom


People also ask

How do I delete multiple comments in R?

The easiest way to create a multi-line comment in RStudio is to highlight the text and press Ctrl + Shift + C. You can just as easily remove the comment by highlighting the text again and pressing Ctrl + Shift + C.

How do you delete items in R console?

The shortest and the quickest way to clear the global environment in R is by using shortcut keys from the keyboards. Simply hit Ctrl+L on the keyboard and you will see that everything written in the console will be erased and the console will be cleared.

How do I uncomment in RStudio?

Comment or uncomment lines with Command + Shift + C on a Mac or Control + Shift + C on Linux and Windows.

How do I remove old codes in R?

Move code blocks through the R script If you need to remove something Ctrl + D will delete the current line/selection in no time.


1 Answers

I wouldn't approach this task with regexes. It may work, but only in simple cases. Consider the following /tmp/test.R script:

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)} #...

As you see, it is a little bit complicated to state where the comment really starts.

If you don't mind reformatting your code (well, you stated that you want the smallest code possible), try the following:

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

which will give /tmp/out.R with:

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

Alternatively, use a function from the formatR package:

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 has a blank argument, which might be of your interest. But I can't get it to work with formatR 0.10 + R 3.0.2...

like image 185
gagolews Avatar answered Sep 28 '22 05:09

gagolews