19 Comments
Guest *jamiefolson* @ 2012-05-18 12:21:15 originally posted:
Could you provide an example? I see the code in hooks-extra, but I'm having trouble getting my own hooks executed. Could you give an Rnw and required compilation commands for using custom hooks?
You can just paste the two pieces of code to set up the hook and use it respectively in an Rnw document like https://gist.github.com/2629886#file_par.rnw
There is nothing special about the compilation; it is normally knit('whatever.Rnw').
Originally posted on 2012-05-18 14:03:18
Guest *ankit sethi* @ 2012-07-06 09:41:41 originally posted:
Hi Yihui,
First of all, congratulations for a fabulous package.
I was comparing Sweave with Knitr for documentation purpose and wanted to compare the output of the two simultaneously. So, I want to know if I can set Sweaveoptions for one chunk and knitr for another in the same .Rnw file. For instance, the R-code using sweave looks like (R-code without background color and in typewriter text) and R-code using knitr looks like(code with background and normal fonts)
Thanks in advance.
Why do you want to put them in the same document? You can generate two tex files separately by:
library(knitr)
render_latex()
knit('file.Rnw', 'file-knitr.tex')
render_sweave()
knit('file.Rnw', 'file-sweave.tex')
Originally posted on 2012-07-06 18:21:05
Guest *ankit sethi* @ 2012-07-08 18:17:23 originally posted:
Creating two tex files wont serve the purpose because I want to show how the R-code or the R-ouput and other graphics look differently in Sweave and knitr by placing the code chunks side by side in the same document.
Well, it is certainly possible but requires deeper understanding of knitr. Here is a quick example: https://gist.github.com/2790354#file_sweave_knitr.rnw
I understand it might be useful for demo purposes, but in practice I do not believe anybody will alternate between the two styles in the same document.
Originally posted on 2012-07-09 01:01:55
Guest *ankit sethi* @ 2012-07-09 17:09:29 originally posted:
Thanks for the example.
Guest *Claas-Thido Pfaff* @ 2012-07-29 13:37:11 originally posted:
He Yihui Thanks for this amazing R package. I'd like to knit my .Rnw files and have some plots in it. I have looked into the .tex output produced by knitr and all the figures are included surrounded by the begin{figure}[htbp] ...end{figure}. I like to draw a frame around the plots with tikz and have defined a node in tikz looking like this.:
tikzstyle{pictureframe} = [rectangle, rounded corners, draw]
I normally surround my other pictures I include into my .tex and .Rnw files by adding a tikzpicture and a the defined node inside the 'figure' environment looking like this:
614 begin{figure}[htbp]
615 centering
616 begin{tikzpicture}
617 node[pictureframe]{%
618 begin{minipage}{0.9textwidth}%
619 begin{center}
620 includegraphics[width=.8linewidth]{figure}
622 end{center}
623 end{minipage}
624 };
625 end{tikzpicture}
626 captionbelow{#2}
627 label{envlabel}
628 end{figure}
I would like my plot figures look as the pictures I include. So how can I realize this? Can you give me a hand with that?
Best Regards Pfaff.
Guest *Mark80305* @ 2012-09-05 04:12:52 originally posted:
Great Package!
One question: In all of your example PDFs, I notice that the light grey background is shown under the R code AND the plots.
When I use your same Rnw code, only the R code has the light grey background -- how do I extend the light grey background to the plots, too?
That was the default behavior of knitr before version 0.4(? I do not remember). Because the gray background interferes with colors in the plots, I decided to move the plots out of the box so they look cleaner. The example PDFs were not updated.
To put plots in the gray box again, you can simply set this in your first chunk: knit_hooks$set(plot = hook_plot_tex).
Originally posted on 2012-09-05 21:01:09
Guest *Stevie P.* @ 2012-09-21 06:24:30 originally posted:
Hi. I was wondering if you could point me to (or post) some examples which successfully use the envir variable inside a hook. I want to create a hook to do some regex work on a certain chunks output, so I thought it'd be clever to try and extract an output variable from that chunk's environment via envir but it just isn't working... Any thoughts?
If you want regex work on chunk output, you can use the chunk hook. For examples on the envir argument, I'm not sure if this helps: https://github.com/yihui/knitr-examples/blob/master/045-chunk-hook.md (source: https://github.com/yihui/knitr-examples/blob/master/045-chunk-hook.Rmd)
Originally posted on 2012-09-21 21:47:46
Guest *Stevie P.* @ 2012-09-23 21:22:47 originally posted:
That was incredibly helpful/illuminating, thank you!
Guest *heeb* @ 2012-11-07 22:16:28 originally posted:
Is it possible to make an output chunk hook that will automatically set output chunk options? For example:
g <- function() cat("hi")
Instead of:
{r results='asis', echo=FALSE}g()
I would like to be able to type
{r myHook=TRUE}g()and by nature of myHook, have the other options automatically specified (echo=FALSE, results='asis'). As far as I understand, I can retrieve the options in the hook function, but I do not know how to set them.
Guest *heeb* @ 2012-11-07 22:17:40 originally posted:
for some reason, new lines didn't work on that post:
Is it possible to make an output chunk hook that will automatically set output chunk options? For example:{r}g <- function() cat("hi")Instead of:{r results='asis', echo=FALSE}g()I would like to be able to type{r myHook=TRUE}g()and by nature of myHook, have the other options automatically specified (echo=FALSE, results='asis'). As far as I understand, I can retrieve the options in the hook function, but I do not know how to set them.
No you cannot change chunk options through a hook function, however, you can store frequently used combinations of chunk options in a template. That is the purpose of opts_template; see ?opts_template which is available in the latest version of knitr.
That said, sometimes I also feed the need to modify chunk options via hook functions. It is entirely possible but requires some internal changes.
Originally posted on 2012-11-08 01:59:21
Guest *JoAnn Alvarez* @ 2012-12-05 21:47:55 originally posted:
Can errors and warnings be written to the terminal, and not in the output document or a separate file? Like in Sweave?
hook_log = function(x, options) cat(x, file='messages.txt', append=TRUE)
knit_hooks$set(warning = hook_log, message = hook_log)
Yes, e.g.
hook_fun = function(FUN) {function(x, options) FUN(x)}
knit_hooks$set(warning = hook_fun(warning), message = hook_fun(message), error = hook_fun(stop))
Originally posted on 2012-12-05 22:55:41
Guest *Andrey Chetverikov* @ 2013-01-10 19:36:41 originally posted:
In case if anyone will look for it, here is a hook that removes all Latex comments from output:
knit_hooks$set(document = function(x, options) gsub("%.*n", '', x,perl=T))
I find it useful when working with mtable function that outputs unnecessary comments.
Thanks for sharing, but I guess this is not 100% safe, because it did not consider the case when % is escaped as %, and also that .* is greedy. Perhaps you need zero-width assertion (?>!=...) for and ? for .*; I did not test it, but I think it should be on the right track.
Originally posted on 2013-01-10 21:08:06
Guest *Andrey Chetverikov* @ 2013-01-11 11:42:00 originally posted:
Ouch, I've completely forgot about %. I'm not sure about *. I know that * is greedy, but I need to remove all stuff after % and till the end of the line, so this seem to be OK. Then correct hook will be gsub("(?
Yes, I think this one should be fine. Thanks!
Originally posted on 2013-01-11 17:47:39
Guest *Rod Alence* @ 2013-02-03 12:20:11 originally posted:
In my lecture slides (Sweave and beamer, with fancyvrb), I use different colors for source (Sinput) and output (Soutput), with something in my preamble like this:
DefineVerbatimEnvironment{Sinput}{Verbatim}{formatcom=color{Blue3}}
DefineVerbatimEnvironment{Sounput}{Verbatim}{formatcom=color{gray}}
I've been able to convert this to knitr successfully using render_sweave(), but I'm wondering (after a few failed attempts) if there's an easy way to do the same thing using output hooks in knitr?
I do not see any problems: https://github.com/yihui/knitr-examples/blob/master/082-sweave-color.Rnw
You had a typo Sounput which should be Soutput, and you also need usepackage[x11names]{xcolor} in order to use the color Blue3.
Originally posted on 2013-02-03 18:11:20
Guest *Rod Alence* @ 2013-02-04 10:34:00 originally posted:
Yihui,
Thanks for the quick reply. I was originally able to get the conversion to work using render_sweave() (with the xcolor option and without the typo (sorry!)).
Where I was stuck was trying to get the same result "directly" using knitr output hooks. My problem was that I didn't realize that I was inserting my formatting (e.g., "color{...") in the middle of a verbatim environment, where it was messing things up.
I solved it by defining the Sinput and Soutput environments (with fancyvrb for the formatting) in my preamble, with knitr hooks for the source and output.
In case anyone else is interested, a minimal(ish) example is:
documentclass{article}
usepackage{fancyvrb}
DefineVerbatimEnvironment{Sinput}{Verbatim}{xleftmargin=1.2em,%
formatcom=color{blue}}
DefineVerbatimEnvironment{Soutput}{Verbatim}{%
formatcom=color{red}}
fvset{listparameters={setlength{topsep}{0pt}}}
begin{document}
<<setup,include=false>>=
require(stringr)
hook.i <- function(x, options) str_c("begin{Sinput}n", x,
"end{Sinput}n")
hook.o <- function(x, options) str_c("begin{Soutput}n", x,
"end{Soutput}n")
knit_hooks$set(source = hook.i, output = hook.o)
opts_chunk$set(comment="#", highlight=FALSE)
@
<>=
2 + 2
@
end{document}
Guest *Remko Duursma* @ 2013-04-02 00:06:58 originally posted:
I found a problem with the prettifying of formulas, when the formula is only one-sided as in xtabs:
xtabs(~ xvar, data=dat)
makes latex,
hlfunctioncall{xtabs}(~dat, data = dat)
Notice the missing space between the ~ and dat! This causes a problem for me, because I used the very nice solution to replace the somewhat ugly default tilde in source code with a nicer, centered one (http://stackoverflow.com/questions/14710477/pretty-tilde-from-r-chunk-with-knitr). When replacing all tildes, the missing space causes havoc!
Thanks for your help.
You can use the chunk option tidy=FALSE to stop knitr from reformatting the code (and removing the space in this case).
Originally posted on 2013-04-02 04:28:51
Guest *Jon* @ 2013-11-06 20:14:37 originally posted:
I am knitting a bunch of R chunks together into an html file. Two chunks are adding calls to jquery resources and I need to remove the duplicate, using a hook. Do you have an example piece of code that does something similar that I might be able to reference?
Guest *Daniel Cher* @ 2014-04-16 00:20:33 originally posted:
Yihui, congratulations on knitr. It's very cool.
I am trying to use knit_hooks to add the following before:
begin{table}[H]
centering
caption{My table caption}
.... then a table generated in R
then after the chunk:
end{table}
I'm using the following:
knit_hooks$set(myTable = function(before, options, envir) {
if (before) {
code to be run before a chunk
str="begin{table}[H]n {centering}n caption{My caption}n"
return(str)
} else {
code to be run after a chunk
return("end{table}n")
}
})
However, I'm seeing "begin{kframe}" and "end{kframe}", which messes things up. I'm not sure how to get rid of these phrases.
One more thing: This removes all "kframe"... and now it works. But the approach seems wrong.
knit_hooks$set(document = function(x) {
gsub('(begin|end){kframe}', '', x)
})
Guest *isomorphisms* @ 2015-02-04 20:57:46 originally posted:
foo_hook = function(before, options, envir) {
In this line, I guess foo is supposed to be replaced with something. (What?) But before, options, envir and are supposed to be written literally as they are? (Because that's the exact word that's already been defined for knitr to look for before knitting.)
Guest *Fábio Salles* @ 2015-12-02 12:10:27 originally posted:
Hi Yihui,
I´m creating a dynamic documet using Rmarkdown/Knitr with many attached figures and tables along different chapters and sections and using package kfigr to citate inline figures/tables resulted from chunks.
I´m facing problems on getting the track of the hierarchical numbering following the chapters/section sequence. The inline output numbering sequence is not following the desired 2 levels (first level for the chapter sequence and second for the figure/table sequence inside that chapter) although the figure/table captions are following the right and desired hierarchical numbering.
How can I fix/set this by calling inline r figr(label, prefix, link, type) or another easy way?
Thanks,
Fabio
Guest *Eduardo W. Ferreira* @ 2016-08-23 19:39:08 originally posted:
Hi Yihui!
Firstly, congratulations for the great work with knitr.
I have a quick question, which I hope can also help others: is there any chunk option to center pander tables? If not, I would love to have some option similarly that for centering plots (set chunk option fig.align='center').
All the best,
Eduardo
Guest *Jerad Acosta* @ 2017-02-10 17:11:29 originally posted:
I LOVE knitr! Thank you for your continued maintenance and further development of this project. I was stoked on R Notebooks (still am) but hope that render_jekyll() output hook will take better fit the majority of my use cases.
Oh, regarding render_jekyll(), I have much better news for you. I think in one week or two, the blogdown package will be ready for public beta testing. The only important thing missing at the moment is the documentation. Once the systematic documentation is done, you will see a whole new world of building websites and blogs. I'm already using blogdown to build my own website, including my blogs and this knitr website (if you have been here before, you probably have noticed a few different things).
Originally posted on 2017-02-10 20:47:18
Guest *Jerad Acosta* @ 2017-02-11 08:25:14 originally posted:
I actually .ust spent a few hours over the last two days playing with a bunch of settings in my Rmd and R Notebook files trying to figure out exactly what's going on.
Think blogdown is ready for the a non webdeveloping Data Hacker to beta? If so, I'll grab it off github, maintain Jerad.xyz, use if for my projects as Jerad.xyz/projects/ and for the other static sites I'm a major contributor to/
It all depends on what you want. For example, if the default theme looks good enough to you, you won't need any knowledge about web development. It is pretty much like WordPress. Similarly, if you can find a theme you like from existing themes, it is also easy to set it up. When you find anything you need to modify, e.g., you need to tweak the CSS or include JavaScript libraries, you will have to know more about the backend engine, i.e. Hugo, as well as website basics (HTML, CSS, JavaScript).
Originally posted on 2017-02-18 04:59:35
Guest *Hamuntu* @ 2017-03-22 13:33:02 originally posted:
Hello,
Joining the happy knitr crew to thank you for these great tools, and also add a quick question: I'm looking for a way to produce a rotated long table in LaTeX from markdown input. I believe output hooks can provide a solution, but could not figure it out ! I would like the chunk output in LaTeX format (longtable environment) to be encapsulated into a landscape environment. Is there a simple way to that please ? The table is produced by a call to pander with chunk option ' results="asis" '. Thanks for your help !!
Guest *Gjalt-Jorn Peters* @ 2019-06-19 16:52:20 originally posted:
The option hooks seem to work a bit differently for the caption, is that possible?
I define a hook for fig.cap that prepends a text. When I verify this using:
> knitr::knit_hooks$get('fig.cap')(list(fig.cap="caption text"))
$fig.cap
[1] "Figure 5: caption text"
It works (yes, it's a figure counter - yes, bookdown does that - but I need custom and deviating text/patterns in the counter prefix).
But when I knit, the hook doesn't seem to be executed. Does this work differently for caption?
(Also: thank you for knitr!!! It is an amazing package that I use quite intensively. Especially now I don't have to continue learning Latex any more (except when exporting to PDFs, but still, much more doable than in the old days. So thank you!!!)
The fig.cap option shouldn't be an exception. I'm not sure if you had a typo in your code: knit_hooks should be opts_hooks.
And thanks for the kind words!
Originally posted on 2019-06-20 04:40:44
Guest *Gjalt-Jorn Peters* @ 2019-06-25 14:51:27 originally posted:
Wow, thanks for the superquick and helpful answer! That was exactly it.
Weird, though - when I run:
?knitr::knit_hooks
I get the page at https://rdrr.io/cran/knitr/man/knit_hooks.html - which provides examples using knitr::knit_hooks$get.
But indeed, when I switch and use knitr::opts_hooks, it works!
In any anybody else needs similar functionality and comes across this, the function I ended up using is at https://gitlab.com/r-packages/ufs/blob/master/R/setFigCapNumbering.R (and will be in the next 'ufs' version on CRAN).
Odd, by the way - ?knitr::opts_hooks has https://rdrr.io/cran/knitr/man/knit_hooks.html as its help page, which links to the knitr::knit_hooks one. I don't see what the difference between the two is from that explanation, but I must be missing something.
In any case, again, thank you so much for Knitr - and for this quick answer!!!
(And, now that I'm 'speaking to you' anyway - also thank you so much for blogdown and bookdown and other things in the Knitr ecosystem! It's great how these packages make it possible to use the same skillset for so many different tasks... So thank you!!!)
Guest *Michel Ballings* @ 2020-01-26 00:26:03 originally posted:
Hi Yihui, I am trying to apply the following hook https://bookdown.org/yihui/rmarkdown-cookbook/hook-hide.html
on a python chunk using reticulate.
<< engine='python'>>=
a = True # SECRET!!
@
It doesn't hide it. It seems to be working on R chunks only. Any ideas on how to make this work on python chunks?
Sign in to join the discussion
Sign in with GitHub