Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the printed output from a function (but still return its value) in R

Tags:

r

I'm trying to have output from a function that prints output not print to the console.

The capture.output function is recommended in some answers, but it's not clear to me how to capture the output but still return the function's output.

E.g., if I have function f() and want "printed output!" to not print to the console but to have "value" be returned:

f <- function() {
    print("printed output!")
    return("value")
}

# printed output is returned - want to capture the output

f()
#> [1] "printed output!"
#> [1] "value"

# also doesn't work, as captured output and function's output is returned

capture.output(f())
#> [1] "[1] \"printed output!\"" "[1] \"value\""

I think the solution may involve using sink (and con()), but the answer that uses them does not use a function (and so I'm having difficulty applying the approach).

like image 791
Joshua Rosenberg Avatar asked Jan 05 '18 18:01

Joshua Rosenberg


People also ask

How do you print the result of a function in R?

Print output using cat() function Another way to print output in R is using of cat() function. It's same as print() function. cat() converts its arguments to character strings. This is useful for printing output in user defined functions.

How do you hide the output of a function?

We can make the output should not appear. By using invisible() function we can suppress the output.

What is capture output in R?

If file is NULL (the default), capture. output returns a character vector. logical flag: if TRUE, the output is appended to file. If FALSE (the default), the output overwrites the contents of file.


1 Answers

Assign the output of the function like this:

capture <- capture.output(result <- f()); result
## [1] "value"
like image 139
G. Grothendieck Avatar answered Oct 02 '22 02:10

G. Grothendieck