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.
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.
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.
Comment or uncomment lines with Command + Shift + C on a Mac or Control + Shift + C on Linux and Windows.
Move code blocks through the R script If you need to remove something Ctrl + D will delete the current line/selection in no time.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With