Reputation: 101
In R, when I print/cat in a function, it is printed properly in stdout when the function is called. When I put the output in a variable via capture.output, the end-of-line character "\n" is missing.
Here is simple R code example:
ff <- function(){ print(-5:-1);cat("dummy line\n");print(1:5)}
ff()
gives the output:
[1] -5 -4 -3 -2 -1
dummy line
[1] 1 2 3 4 5
and the following code gives output in single line.
ff_out<-capture.output(ff())
ff_out
gives the same output in one line (i.e., with "\n" missing)
I must be missing something very simple. Please help me resolve this to get the same output as shown above.
Upvotes: 2
Views: 484
Reputation: 66819
It's not actually "in one line". It's a vector of length three, where each element is one of the lines. You can
cat(ff_out, sep="\n")
# [1] -5 -4 -3 -2 -1
# dummy line
# [1] 1 2 3 4 5
To inspect an object, str
is useful, like
str(ff_out)
# chr [1:3] "[1] -5 -4 -3 -2 -1" "dummy line" "[1] 1 2 3 4 5"
The part at the start indicates that it is a character vector of length three.
Upvotes: 1