pogibas
pogibas

Reputation: 28339

Transform function to a character string without losing comments

I want to transform functions to a character strings. I can't directly transform class function to a class character, thus I'm using function to list to character logic. However, list removes comments from functions.

Example:

foo <- function() {
    1 + 1
}
# Can't use as.character(foo), thus:
as.character(list(foo))
    "function () \n{\n    1 + 1\n}"

However, if function contains comment then it gets removed

bar <- function() {
    # sum
    1 + 1
}
as.character(list(bar))
    "function () \n{\n    1 + 1\n}"

Question: Why list removes comments from functions and how to save them? Or what is a better way to transform functions to character strings?

Edit: Suggestion by MrFlick to use capture.output works for interactive R session. However, if use code.R:

bar <- function() {
    # sum
    1 + 1
}
# collectMetaData()
print(paste0(capture.output(print(bar)), collapse="\n"))

And try to run it with Rscript code.R my output is still: "function () \n{\n 1 + 1\n}"

Upvotes: 1

Views: 123

Answers (1)

Roland
Roland

Reputation: 132706

I have no idea, why you'd want to do that. This looks like an xy problem. Anyway, you seem to want to deparse the function:

bar <- function() {
  # sum
  1 + 1
}

paste(deparse(bar, control = "useSource"), collapse = "\n")
#[1] "function() {\n  # sum\n  1 + 1\n}"

Upvotes: 3

Related Questions