print the data.table package's .onAttach messages with knitr - r

I have a bookdown rmd looking like...
Further introductory materials are offered when the package is loaded:
```{r dt-startup, echo=-1, message=TRUE, verbose=TRUE, hide=FALSE}
if ("data.table" %in% .packages()) detach("package:data.table")
library(data.table)
```
My intention was to show the reader the package's startup messages. However, they don't print. Is there some other chunk option to use here?
As you can see, I just threw several maybe-relevant chunk options at it to no good result. I'm not terribly familiar with management of output streams, so that's as far as I knew to go. I also tried calling directly with data.table:::.onAttach(), but no dice.
I'm not sure what else would be relevant here, but ...
Currently the package has not been loaded before this chunk. I just added the first line for robustness in case I rearrange the document.
My before_chapter_script contains nothing but knitr::opts_chunk$set(comment="#").
My knit header value is bookdown::render_book and the output is bookdown::html_book.

Don't. Anything hacked in for this would be fragile and arguably not terribly useful.
Yihui Xie (knitr's author) makes a good case. My synopsis:
This is not useful. You're writing a tutorial, so why include dynamic content (that may change when the package changes)? Moreover, why not point to resources directly rather than to the list of resources printed there?
This is very hard. It is not just a matter of output streams. The messages don't print because they are walled behind an interactive() check. It's not obvious how this should be overridden and, supposing it could be done, what weird side effects that might introduce.

Related

knitr: Referring to and evaluating external code chunks

How could I refer to and evaluate (in an .Rmd file) specific chunks of R code, located not in a different .Rmd file, but in an R module, containing chunks of code, tagged with ## #knitr chunk_name? Thanks!
I just figured out what the problem was: I have simply forgotten to call read_chunk() function for the R module, containing those external code chunks. So far, everything appears to be working, with the exception, mentioned below.
One problem I'm currently experiencing (and this might be a good separate question, but I'll leave it as is for now) is that knitr doesn't seem to respect working directory and paths, constructed on its basis, using relative paths, such as file.path(getwd(), "data/transform"). I think this contradicts with knitr design, which allows code reuse via chunks in external R modules. What are approaches that people are using to solve this peculiar situation? I believe that it might be a good idea to submit as a feature request.

How to get help on Rmarkdown chunks options?

I started to play with Rmarkdown and I'm loving it. But I have newbbie question that, ridiculous or not, I can't find a straight forward answer:
I can't figure where in knitr documentation or elsewhere I can learn what are the useful things to write in the chunks insert to tell R what to plot or not. E.g:
```{r warnings=FALSE, message=FALSE}
Will prevent R messages and warnings to appear in the HTML output. I saw this in another question, and I am wondering how to figure things like that by myself using ? or similar.
Thanks.
Have you looked # the documentation yihui provides on the knitr site?
I also highly recommend checking out his book he recently released dynamic documents with R and Knitr he covers everything you'd reasonably use and then some.
You can also easily explore the options in R studio by creating an R chunk
}```
adding a comma
```{r,
}```
and pressing tab after the comma and it will give you all the potential options - they are well named and you can easily focus your search more thoroughly. For example, if you noticed the `purl` option you could explore more and find it is for extracting R code from the chunk.

Make Sweave or knitr put graphics suffix in `\includegraphics{}`

I just run into the (curious) problem that when submitting a (pdf)LaTeX manuscript to some Elsevier journal the filenames of figures needed to be complete in order to found by their pdf building and checking syste, i.e.:
\includegraphics{picture.pdf}
Is there any easy and convenient way to tell Sweave or knitr to do that?
Edit:
I'm familiar with sweave's include=FALSE option
I also feel quite capable to patch utils:::RweaveLatexRuncode
However, for the moment I'm hoping that there's something more convenient and elegant.
It's also about handing out the .Rnw files as supplementary material or vignettes. From a didactic point of view I don't like these tweaks that make the source code much more complicated for the new users of whom I hope they read it.
(Which is also why I really appreciate the recently introduced print=TRUE in Sweave)
You can modify the plot hook a little bit in knitr to add the file extension:
<<>>=
knit_hooks$set(plot = function(x, options) {
x = paste(x, collapse = '.') # x is file.ext now instead of c(file, ext)
paste0('\\end{kframe}', hook_plot_tex(x, options), '\\begin{kframe}')
})
#
See 033-file-extension.Rnw for a complete example. To understand what is going on behind the scene, see the source code of the default LaTeX hooks in knitr.
A brute force solution is to explicitly create the files yourself in the R snippet. Set the option for graphics etc to false but have the code evaluated so that the file is created, and then have latex call them with the very \includegraphics{} call you show.
I used similar schemes for simple caching: if the target file exists, skip the code creating.

what does it mean that "cacheSweave doesn't cache side-effects"?

I'm using cachesweave, but I don't think I get how everything works. I've tried to separate the code into simulation chunks and the plotting chunks, but some of the code is very long and written before I started the sweave document, so I instead use something like
<<foo,cache=TRUE>>
source("mainScript.R")
#
<<plot,fig=TRUE>>
a<- print(str(F1))
plot(F1)
#
The thing is mainScript.R is somewhat convoluted simulation code including plot functions and so on. I've read in cacheSweave vignette "cacheSweave doesn't cache side-effects" and plots are not cached, so I was wondering if the plotting functions in mainScript.R effect how the expressions are evaluated?
This might be an obvious question. Let's say I have another chunk after the two above. all of the results of the expressions in both "foo" and "plot" can be used in this new chunk, right? For example,
<<post-chunk>>
print(a)
print(str(F1))
#
See Wikipedia for a full explanation. Some common side-effects in R include: print() objects, draw plots, write files and load packages.
The cacheSweave package only enables you to skip computation, and you have to lose all side-effects. As Dason commented, the knitr package is much more natural in terms of caching -- what you see in an uncached chunk will be seen in the cached chunk. The caching of side-effects in knitr is explained in its manual and the cache page in the website.
BTW, knitr keeps compatibility with Sweave and cacheSweave, so hopefully you do not need to do anything for the transition; just call library(knitr); knit('file.Rnw').

Silencing a package load message in Sweave

I'm loading optmatch in a Sweave document as follows:
<<myCodeBlock, echo=FALSE>>=
library(optmatch, quietly=TRUE)
#
You're loading optmatch, by Ben Hansen, a package for flexible
and optimal matching. Important license information:
The optmatch package makes essential use of D. P. Bertsekas
and P. Tseng's RELAX-IV algorithm and code, as well as
Bertsekas' AUCTION algorithm and code.
Bertsekas and Tseng freely permit their software to be used for
research purposes, but non-research uses, including the use of it
to 'satisfy in any part commercial delivery requirements to
government or industry,' require a special agreement with them.
By extension, this requirement applies to any use of the
fullmatch() function. (If you are using another package that has
loaded optmatch, then you will probably be using fullmatch indirectly.)
For more information, enter relaxinfo() at the command line
As you can see, I've tried every way I can think of to silence the package load message, to no avail. I assume this is because they just used a straight-up cat() or something like that, but it's mighty annoying. Any thoughts on how to silence this so that those reading my final, beautiful, LaTeXified PDF don't have to read about RELAX-IV?
Other things that don't seem to work (take from Andrie's pointer to a related thread):
suppressMessages(library(optmatch))
suppressPackageStartupMessages(require("optmatch"))
I should note this is pretty obviously an R problem not a Sweave problem, as the messages pop up in R also.
Try loading the package in a hide results chunk:
<<packages,results=hide>>=
require(optmatch)
#
If you use the knitr package, you need to quote hide:
<<packages,results='hide'>>=
require(optmatch)
#
Here is an R solution to your problem. The package author uses cat to print the messages to the console, rather than using standard message statements. You can intercept these messages by using sink to divert console output to a temporary file:
<<myCodeBlock, echo=FALSE>>=
zz <- tempfile()
sink(file=zz)
library(optmatch, quietly=TRUE))
unlink(zz)
#
PS. The solution by #XuWang uses only SWeave, so is clearly much more suitable in your case.

Resources