cesarsalgado
cesarsalgado

Reputation: 1026

How to print output to a variable instead of stdout?

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.

Upvotes: 2

Views: 527

Answers (1)

cesarsalgado
cesarsalgado

Reputation: 1026

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") 

Upvotes: 3

Related Questions