3

I am looking for a way to put inline latex code into a R code chunk in Knitr. Here is my example code from the knitr example site :

\documentclass{article}
\begin{document}
Example text outside R code here; we know the value of pi is \Sexpr{pi}.
<<my-label, echo=FALSE, eval=TRUE>>=
set.seed(1213)  # for reproducibility
x = cumsum(rnorm(100))
m <- mean(x)  # mean of x
print(m)
cat(m)
plot(x, type = 'l')  # Brownian motion
@
\textit{Mean is :} \textbf{\Sexpr{m}}
\end{document}

For something simple like this is I could use result='asis' but for a more complicated piece of code, where you want to periodically write the result out to the document, (especially you have complex ggplot graphs), that solution does not work very well.

In the given example, I have 3 queries :

  1. How would I use inline latex code for the output from line 8, in case I wanted to color, bold etc. that text.
  2. Can one eliminate the grey box that appears when we use the cat or print command.
  3. Can the numbering which appears with the print command, which is eliminated with the cat command be eliminated for the print command as well, since print has many variants in many packages for data frames data tables etc. and might be more commonly used to print a portion of data.

In summary, I am mainly looking for the inverse of line 12 in the code.

I have also unsuccessfully tried knit_print with printr, and asis_output, in lieu of print. Although I may have been incorrectly using them.

Thanks!

TryingR
  • 31
  • 1
  • On your first question, do you mean is there some way to have print(m) in the chunk be something like print(m, color = "red", fontface = "bold", etc.) but with LaTex code? Sort of like print(m, Latex::{\textcolor{m), etc)? Or do you mean to calculate m in the chunk and format it outside the chunk? – lawyeR Dec 12 '15 at 19:06
  • Thanks for replying lawyeR. I am referring to your later option as in : `print(m, latex::...)`. I thought the function `asis_output` would do the trick. So if I were to use something like : `asis_output('\emph{Mean is : \color{red} m }')`, then the string within the parenthesis would be sent to latex directly. However this does not seem to work, or I am not using `asis_output` correctly. – TryingR Dec 13 '15 at 00:55
  • I tried variations on results = 'asis' in the chunk header, but couldn't get latex commands to work with the R code. Sorry – lawyeR Dec 13 '15 at 02:40
  • I feel there is a way to do this `knitr_hooks` but I am not quite sure how. – TryingR Dec 13 '15 at 18:17
  • Not sure if I get the question, but are you simply looking for something like `asis_output(sprintf('\\emph{Mean is : \\color{red} %1.4f }', pi))`? – CL. Dec 14 '15 at 08:32

0 Answers0