Search code examples
rsweave

Put a part of a text in bold in \sexp with Sweave


I used a condition to display 2 differents text with Sweave. After that, I display this text.

But I would like to bold a part of my first text.

<<condition, echo=FALSE>>=
if (x > 0) {
  text <- paste("text 1 start :",paste(variables, collapse = ","), ". text 1 end.")
  } else {
    text <- paste("text 2")
  }
@

\Sexpr{text}

Here, the actual output in my report.pdf is:

text 1 start : var1, var2, var3 text 1 end

But I would like :

text 1 start : var1, var2, var3. text 1 end


Solution

  • You could return your data separately and use the normal LaTeX commands like \Sexpr{foo} \textbf{\Sexpr{bar}} \textbf{\Sexpr{foobar}}.

    Alternatively, you could embed the necessary LaTeX command in R like this:

    \documentclass[A4]{article}
    \begin{document}
    <<>>=
    foo <- paste(1, 2, "\\\\textbf{", 3, "}", '4')
    @
    
    Test text with some \Sexpr{foo} with formatting.
    \end{document}
    

    Mind the multitude of backslashes necessary.

    Edit:

    For knitr the code needs some modificaitions:

    \documentclass[A4]{article}
    \begin{document}
    <<>>=
    foo <- paste(1, 2, "\\textbf{", 3, "}", '4')
    @
    
    Test text with some \Sexpr{asis_output(foo)} with formatting.
    \end{document}