4

Suppose I have:

test <- function(x) x + 1
test
function(x)
  x + 1

I would like to somehow save the output produced by invoking test to a string (i.e. the function declaration) but can't think of a way to do it.

3
  • Do you need "x + 1" Commented Jul 24, 2019 at 15:17
  • I would like the full string: "function(x) x + 1" Commented Jul 24, 2019 at 15:19
  • Is this after you declare the test. Something like deparse(test) Commented Jul 24, 2019 at 15:20

3 Answers 3

6

We can use deparse

paste(deparse(test), collapse = " ")
#[1] "function (x)  x + 1"

Also, if we need to extract the components of the function, use body

body(test)

Or split it to a list

as.list(test)
Sign up to request clarification or add additional context in comments.

Comments

6

You are looking for capture.output.

> z=paste(capture.output(test), collapse = " ")
> z
[1] "function(x) x + 1"

3 Comments

This works but was hoping this was going to be the last-resort solution. Is there anything better other than capture.output? No other function to just dump the definition of a function?
Coming from other programming languages (.NET, Java, etc.), creators of libraries would always love to change their toString() method so it prints their object more succinctly or prettier, etc. Having your production app and its reputation depend on how an object is printed on the command-line by a third-party developer you have no access to is generally not an accepted practice in most languages I am familiar. R is new to me so maybe the rule breaks on this one.
@Denis, in R, sometimes complex objects (or more specifically, their classes) will have print.yourclass methods, but I've never seen that for a standalone function.
2

Another possibility?

dput(test,textConnection("test_txt",open="w"))

or the same with dump()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.