16

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

Joshua Rosenberg
  • 4,014
  • 9
  • 34
  • 73

1 Answers1

22

Assign the output of the function like this:

capture <- capture.output(result <- f()); result
## [1] "value"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • 4
    You could also just wrap the whole thing in `invisible` instead of assigning to a value `invisible(capture.output(result <- f()))` – Dason Jan 05 '18 at 18:57
  • It might be useful to the questioner to explain that `<-` is a function that returns the value of its RHS as well as effecting an assignment to a symbol. – IRTFM Jan 05 '18 at 19:53
  • @42- I think that makes sense – Joshua Rosenberg Jan 06 '18 at 15:12