For non-primitive functions, R base includes a function called body()
that returns the body of function. For instance the source of the print.Date()
function can be viewed:
body(print.Date)
will produce this:
{
if (is.null(max))
max <- getOption("max.print", 9999L)
if (max < length(x)) {
print(format(x[seq_len(max)]), max = max, ...)
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max, "entries ]\n")
}
else print(format(x), max = max, ...)
invisible(x)
}
If you are working in a script and want the function code as a character vector, you can get it.
capture.output(print(body(print.Date)))
will get you:
[1] "{"
[2] " if (is.null(max)) "
[3] " max <- getOption(\"max.print\", 9999L)"
[4] " if (max < length(x)) {"
[5] " print(format(x[seq_len(max)]), max = max, ...)"
[6] " cat(\" [ reached getOption(\\\"max.print\\\") -- omitted\", "
[7] " length(x) - max, \"entries ]\\n\")"
[8] " }"
[9] " else print(format(x), max = max, ...)"
[10] " invisible(x)"
[11] "}"
Why would I want to do such a thing? I was creating a custom S3 object (x
, where class(x) = "foo"
) based on a list. One of the list members (named "fun") was a function and I wanted print.foo()
to display the function source code, indented. So I ended up with the following snippet in print.foo()
:
sourceVector = capture.output(print(body(x[["fun"]])))
cat(paste0(" ", sourceVector, "\n"))
which indents and displays the code associated with x[["fun"]]
.
Edit 2020-12-31
A less circuitous way to get the same character
vector of source code is:
sourceVector = deparse(body(x$fun))