Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sink() won't print output to text file in rmarkdown

Say I have a simple rmarkdown document called test.Rmd

---
output: pdf_document
---

This code tries to save output to a file called 'example.txt'
```{r}
sink(file='example.txt')
sink.number()
library(MASS)
summary(cars)
sink()
sink.number()
```

If I run this in RStudio (using the knit PDF button) then I get lots of output but I believe the most important is the following (I can include the other output on request)

processing file: test.Rmd

"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS test.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output test.pdf --template "C:\Users\wammonj\Documents\R\win-library\3.2\rmarkdown\rmd\latex\default.tex" --highlight-style tango --latex-engine pdflatex --variable graphics=yes --variable "geometry:margin=1in" 
output file: test.knit.md


Output created: test.pdf
Warning message:
In sink() : no sink to remove

The file example.txt is made but the output is not in there while Rmarkdown made a file called test.pdf with the output of summary(cars) in it.

Is that the problem? Does Rmarkdown use sink() to make its documents? Is there a way around this so the output will appear in both the pdf file and the text file?


Addition: It looks like from @r2evans comment that rmarkdown does indeed use sink(). I have played with sink() a little and it seems like you can have multiple diversions going at the same time but you can only write to the one that was most recently activated (see example below).

So it seems from the output that Rmarkdown closes my sink down right away because when I look at sink.number() then it is always one.

I am still trying to find a workaround for this so any help would be nice.

Example of multiple diversions:

sink(file = 'example1.txt')
sink(file = 'example2.txt')
sink.number() # prints 2 to example2.txt
x = seq(1,10)
x # prints to example2.txt
sink()
sink.number() # prints 1 to example1.txt
y = sum(x)
y # prints to example1.txt
sink()
sink.number() # prints 0 to R console
like image 854
MathIsKey Avatar asked Nov 08 '22 10:11

MathIsKey


1 Answers

I run into a similar issue. One solution of saving the output to local files is to use write.csv() function instead, which also works with non-csv files.

The R code below tries to save output to a file called 'example.txt'.

write.csv(data.frame(data_to_save), file='example.txt')

like image 63
Jm M Avatar answered Nov 15 '22 08:11

Jm M