简体   繁体   中英

Capture the printed output from a function (but still return its value) in 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.

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

Assign the output of the function like this:

capture <- capture.output(result <- f()); result
## [1] "value"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM