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

帅比萌擦擦* 提交于 2020-12-30 17:22:16

问题


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

回答1:


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')



来源:https://stackoverflow.com/questions/39131017/sink-wont-print-output-to-text-file-in-rmarkdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!