Output to external file via sink() method

741 views
Skip to first unread message

firef...@gmail.com

unread,
Feb 3, 2014, 5:25:12 PM2/3/14
to kn...@googlegroups.com
Hello,

I have the following R code in Lyx + Knitr.  I would like to have R run and create an external correlation HTML file.  The code is running successfully, however, the actual HTML contents are being displayed inside my Knitr PDF document that is generated.  Is it possible to move this out into the other file?  I can run the exact same code straight in R and it works fine.

<<Correlation_Table, echo=FALSE, message=FALSE>>=
sink("correlation_table.html", append=FALSE, split=FALSE)

library("xtable")
library("Hmisc")

corstarsl <- function(x){
#create table code here...
}

sprintf("correlation table:")
print(xtable(corstarsl(data[,c(19:22)])), type="html")
sprintf("<p>p < .001 = ***</p><p>p < .01 = **</p><p>p < .05 = *</p>")

#finish output to file
sink()
@


Thanks.

-Patrick

Yihui Xie

unread,
Feb 3, 2014, 8:17:13 PM2/3/14
to firef...@gmail.com, knitr
You can use the chunk option results='hide'. In this case, you
probably do not want anything from this chunk to be in the output, so
just use a single chunk option include=FALSE (no need to specify other
options such as echo or message).

Regards,
Yihui
--
Yihui Xie <xiey...@gmail.com>
Web: http://yihui.name

firef...@gmail.com

unread,
Feb 4, 2014, 10:48:38 AM2/4/14
to kn...@googlegroups.com, firef...@gmail.com
Hello,

Thanks for the reply.  I tried:

<<Correlation_Table, include=FALSE>>=

However, the resulting HTML file is empty.  There is no output to the resulting PDF file (which is expected).  Is there another way or something wrong with using "print" and "sprintf"?

-Patrick

Yihui Xie

unread,
Feb 4, 2014, 11:26:01 PM2/4/14
to firef...@gmail.com, knitr
I see. Unfortunately sink() will not work in knitr, because it is
already used internally to capture results. You have to wrap up all
the code in a single expression, e.g.

{
sink('foobar.txt')
print(1:10)
sink()
}

BTW, you were actually abusing the sprintf() function -- you really
only need print(), and sprintf() was not designed for printing a plain
character string, although it worked coincidentally.

Regards,
Yihui
--
Yihui Xie <xiey...@gmail.com>
Web: http://yihui.name


firef...@gmail.com

unread,
Feb 5, 2014, 10:55:56 AM2/5/14
to kn...@googlegroups.com, firef...@gmail.com
Ahh super, that worked.  Thanks for the help and for developing this great app!

-Patrick
Reply all
Reply to author
Forward
0 new messages