I am trying to write an Rscript from within R. Using quote()
with the $wholeSrcref
attribute works well when on its own. However, additional unwanted lines are written when used within a function. Details are as provided below.
My first attempt was to quote()
the expression, followed by writing the quoted expression to file, that is,
expr <- quote({
a <- 1 # comment 1
b <- 2 # comment 2
})
writeLines(tail(as.character(expr), -1), file)
However, comments in the code are not written to file. A workaround would be to use the $wholeSrcref
attribute, as given by this answer. My second attempt:
library(magrittr)
expr <- quote({
a <- 1 # comment 1
b <- 2 # comment 2
})
attributes(expr)$wholeSrcref %>% as.character() %>%
tail(-1) %>% # remove '{'
head(-1) %>% # remove '}'
writeLines(file)
This works well. However, when wrapping this within a function, part of the function's body is also prepended to the quoted expression. That is, given the following code,
library(magrittr)
f <- function(dir) {
# change directory to dir
# do stuff
expr <- quote({
a <- 1 # comment 1
b <- 2 # comment 2
})
attributes(expr)$wholeSrcref %>% as.character() %>%
tail(-1) %>% # remove '{'
head(-1) %>% # remove '}'
writeLines(file)
# do more stuff
}
f(dir="")
The file would contain
# change directory to dir
# do stuff
expr <- quote({
a <- 1 # comment 1
b <- 2 # comment 2
How can I write only the quoted expression to file?