[R] Sweave: Incorporating warnings into a Sweave output chunck

Duncan Mackay dulcalma at bigpond.com
Wed Jan 4 04:07:34 CET 2017

Dear All

There are some occasions I have run code in R without warning. 
After incorporating the code into an .Rnw file and running by Sweave I find
there are  warnings sent to the screen.  

On some occasions when I use Sweave(...)  I would like to incorporate the
warnings into the resulting tex file.
Until now I have done it manually which is a bit of a pain.

Does anyone know of a way?  It would be nice to have a Sweave option to
include it.

The only reference I can find is 


which had no replies except this one on Nabble


I have got the code from the attached Rnw file working in R version 3.3.1 
But there are some problems with it.

Below is  the code including some of the options and setup with the function
in one chunck
<<redefwarning, echo=FALSE>>=
  options(warn = 1)
  cons <- showConnections(all = TRUE)
 # .CurFileName <- get("file", env = parent.frame(3)) # modified by next
  .CurFileName <-
  subset(data.frame(cons), class == "file" & nchar(description) > 0)[1]) )
  .PrefixName <- strsplit(.CurFileName, "\\.")[[1]][1]
  .LatexFileName <- paste(.PrefixName, "tex", sepo = ".")
  .LatexFileCon <-
  getConnection(what = as.integer(rownames(cons)[which(cons[,1] ==
  sink(file = .LatexFileCon, append = TRUE, type = "message")

warningbck <- warning
warning <-
function (..., call. = TRUE, immediate. = FALSE, domain = NULL){

  args <- list(...)

  if (length(args) == 1 && inherits(args[[1]], "condition")) {

    cond <- args[[1]]
    message <- conditionMessage(cond)
    call <- conditionCall(cond)

      .Internal(.signalCondition(cond, message, call))
      .Internal(.dfltStop(message, call))
    muffleWarning = function() NULL)


  }  else {

    if (length(args) > 0) {

      args <- lapply(list(...), as.character)

      if (is.null(domain) || !is.na(domain))
        args <- .Internal(gettext(domain, unlist(args)))
        message <- paste(args, collapse = "")

    } else{

      message <- ""

    writeLines(text = "\n\\end{Sinput}\n\\begin{Soutput}", con =
    .Internal(warning(as.logical(call.), as.logical(immediate.), message))

    writeLines(text = "\\end{Soutput}\n\\begin{Sinput}", con =

This puts the warning into the input chunck directly after the R command
e.g. as shown below

  clust.hw <- svydesign(ids = ~Patient, data = hw.dat)Warning in
svydesign.default(ids = ~Patient, data = hwd) :
  No weights or probabilities supplied, assuming equal probability


I think that there also needs to be an argument about closing connections
somewhere in the code.



Duncan Mackay
Department of Agronomy and Soil Science
University of New England
Armidale NSW 2351
Email: home: mackay at northnet.com.au

More information about the R-help mailing list