'How can I write code containing comments to a file, using an R function?
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?
Solution 1:[1]
Well, the easiest approach would be to count the lines above the quote function and adjust the tail function to exclude these rows. Admittedly, it's not very elegant
f <- function(dir) {
# change directory to dir
# do stuff
expr <- quote({
a <- 1 # comment 1
b <- 2 # comment 2
})
exclusion_line <- which(grepl("expr <- quote({",
attributes(expr)$wholeSrcref %>% as.character(),
fixed = TRUE))
attributes(expr)$wholeSrcref %>% as.character() %>%
tail(-exclusion_line) %>% # remove '{'
head(-1) %>% # remove '}'
writeLines(file)
# do more stuff
}
f(dir="")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | starja |
