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).
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.
We can make the output should not appear. By using invisible() function we can suppress the output.
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.
Assign the output of the function like this:
capture <- capture.output(result <- f()); result
## [1] "value"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With