Skip to content
Back to formatted view

Raw Message

Message-ID: <4D0143EB.5080308@gmail.com>
Date: 2010-12-09T21:02:35Z
From: Duncan Murdoch
Subject: How does Sweave write to a file?
In-Reply-To: <3B50C236-3736-4DE1-AA20-05CD1E6B07FA@uib.es>

On 09/12/2010 2:07 PM, Arnau Mir Torres wrote:
> Hello.
>
> I need that Sweave writes R output to a file. To do it, I put the following into the foo.Rnw file:
>
>
> \documentclass{article}
> \usepackage{Sweave}
> \begin{document}
>
> ...
>
> <<echo=F>>=
> x<- rnorm(100)
> y<- rnorm(100)
> sink("foo.txt")
> summary(lm(y~x))
> sink()
> @
>
> ...
>
> \end{document}
>
>
> When I run:
>
> R CMD Sweave foo.Rnw
>
> R responses:
>
> Warning message:
> In sink() : no sink to remove,
>
> and It doesn't work. Somebody knows how I can fix it?


The problem is that Sweave executes each statement wrapped within sink( 
con ); statement; sink().  You need to avoid using sink() as a separate 
statement.  One way would be to put the lines

sink("foo.txt")
summary(lm(y~x))
sink()

into a block using braces {}; Sweave would wrap the whole function call, not the individual lines.  That's essentially what
capture.output() does, so this should work:

writeLines( capture.output( summary(lm(y~x)) ), "foo.txt")

You can probably do it in other ways too.

Duncan Murdoch