2

I want to convert an object to a string representation of it in the same way that the print() function does. But I also want to store that string in a variable instead of sending it to stdout. For example:

When I enter print(mtcars) it will print the data frame in a pretty way. But when I use the toString method it will convert to a string like: c(21, 21, 22.8, ...), c(6, 6, 4, ....), ... (I used ... to shorten the output).

But I would like the string to be in the same format as the print() function. It would be nice if there was an sprint function that takes any variable as input. There exists sprintf, but then I will have to know the type of the object before hand.

I saw something about using results <- capture.output(...) but it seemed too complex. There should be a easy way to do that.

1
  • 5
    You've answered your own question; that's what capture.output does, e.g. mtcars_lines <- capture.output(mtcars) will store a character vector of lines captured from the print method of mtcars. Commented Jan 25, 2018 at 17:56

1 Answer 1

3

The comment of @alistaire was right. I can simply use capture.output. But I still need to paste the lines together. So my final solution is:

paste(capture.output(mtcars), collapse="\n") 
Sign up to request clarification or add additional context in comments.

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.