From bbolker at gmail.com  Sun Sep 22 19:03:45 2013
From: bbolker at gmail.com (Ben Bolker)
Date: Sun, 22 Sep 2013 13:03:45 -0400
Subject: [Rd] type="message" possibility for capture.output() ?
Message-ID: <523F22F1.9010105@ufl.edu>


  As far as I can tell, there's no built-in way to get
capture.output() to capture messages (stderr) instead of
stdout ... suggested, fairly trivial, patch below.

f <- function() {
    message("abc")
    cat("def\n")
}

x <- capture.output(f())
## prints 'abc'
x ## value: "def"

source("~/R/r-devel/src/library/utils/R/capture.output.R")
x <- capture.output(f()) ## unchanged
x <- capture.output(f(),type="message") ## prints 'def': value 'abc'

   Of course, if someone was going to mess with this function more,
it might be nice to have an option to have *both* streams captured ...

Index: capture.output.R
===================================================================
--- capture.output.R	(revision 63969)
+++ capture.output.R	(working copy)
@@ -16,8 +16,10 @@
 #  A copy of the GNU General Public License is available at
 #  http://www.r-project.org/Licenses/

-capture.output <- function(..., file=NULL, append=FALSE)
+capture.output <- function(..., file=NULL, append=FALSE,
+                           type = c("output", "message"))
 {
+    type <- match.arg(type)
     args <- substitute(list(...))[-1L]

     rval <- NULL; closeit <- TRUE
@@ -31,9 +33,9 @@
     } else
         stop("'file' must be NULL, a character string or a connection")

-    sink(file)
+    sink(file,type=type)
     ## for error recovery: all output will be lost if file=NULL
-    on.exit({sink(); if(closeit) close(file)})
+    on.exit({sink(type=type); if(closeit) close(file)})

     pf <- parent.frame()
     evalVis <- function(expr)
@@ -50,7 +52,7 @@
     }
     ## we need to close the text connection before returning 'rval'
     on.exit()
-    sink()
+    sink(type=type)
     if(closeit) close(file)
     if(is.null(rval)) invisible(NULL) else rval
 }



[Rd] type="message" possibility for capture.output() ?
Ben Bolker