Using R Markdown in knitr is there an equivalent to \Sexpr{}
in Sweave?
2 Answers
Yes. You can use
`r your_expression_here`
So something like
2+2 is: `r 2+2`
Should produce:
2+2 is: 4
I initially found it a little difficult trying to figure out what the different syntax was for each of the different styles you could use in knitr (html, markdown, sweave, ...) and resorted to looking at Yihui's minimal examples (which do a good job) but if you can read regular expressions you can view the default pattern definitions. You even have the option of defining your own syntax if you want.
-
It's advertised that you can change the default pattern, but if you try, you will be asked by Yihui why you want to do it. Strange, after so many other things were changed, and for good reasons. github.com/yihui/knitr/issues/226 Commented May 17, 2012 at 9:30
-
5I thought no one could read regular expressions. Aren't they a write-once non-language? :-) Commented May 17, 2012 at 14:16
-
Initially to set up the parsing sure it takes more work but I guess it could save some typing in the long run if you write a lot of inline stuff. Plus I know I've thought about messing around and changing some of those. Why? Because you gave us the option to do that :p– DasonCommented May 17, 2012 at 19:10
-
2@Dason haha, yes, you can mess with many things in knitr, and if you go away from the default settings, you just need to be aware of reproducibility for other people (need to give them more instructions on how to compile the document) Commented May 23, 2012 at 15:58
By default inline R code in R Markdown will be formatted as code. If you just want output to appear asis
then inclose the R command in I(...)
. Enclosing output with I(...)
matches the behaviour of Sexpr
. This distinction is sometimes important. For more information, see this comment by Yihui Xie. The following table shows the different output from R Markdown to Markdown to HTML.
R Markdown `r 2 + 2` `r I(2+2)`
Markdown `4` 4
HTML <code>4</code> 4
-
3