How to layout character value within R chunk

若如初见. 提交于 2019-12-12 03:18:49

问题


In the knitr package I like the kable function. It gives a nice layout of tables and data frame like objects even as it is called from within an R code chunk. Now I want to do the same thing with a character value. Is there a function that gives a kable-like output ("kprint") that can be formated?

knitr::kable() # exists for tables
knitr::kprint() # does a function like this exists for character values?

This is what I get now:

print("character value") # within the R Chunk 

Output in generated report:

## [1] "character value"

And this is what I want, just:

character value

EDIT cat("character value") is not the solution I am looking for because I don't want an R output anymore, but just a plain text.


回答1:


There are two things to do to get a "raw" character string (without any formatting or additional output like [1]) from R to TEX:

  • Use the chunk option results = "asis" to instruct knitr not to modify the output.
  • Use cat instead of print because print adds the lenght of the vector and quotes to the output.

In this context, inline output using \Sexpr{} might be useful because values in \Sexpr{} are by default printed "as they are": \Sexpr{myoutput}.

As there was the question of how to format the output in the comments, here some options:

  • Add LaTeX to the text you pass to cat: cat("\\emph{foo}"). Don't forget to escape \ by an additional \.
  • Do the same thing as above, but use a function to do the "dirty work":

    makeItNiceR <- function(x) {
      return(paste("\\fbox{\\texttt{", x, "}}"))
    }
    
    cat(makeItNiceR("foo bar is nice"))
    
    • (Note that we could use cat inside makeItNiceR to save some typing, but this makes the function less flexible and we cannot use it in combination with \Sexpr{} anymore.)
  • Manually add LaTeX formatting commands around \Sexpr{}:

    Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX.
    
  • Combine makeItNiceR and \Sexpr{} to get nicely formatted output from \Sexpr{}:

    \Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
    

The following minimal examples demonstrates the usage of all code snippets from above:

\documentclass{article}
\begin{document}

<<results = "asis">>=
makeItNiceR <- function(x) {
  return(paste("\\fbox{\\texttt{", x, "}}"))
}

myoutput <- "slim"

cat("foo")
cat("\\emph{foo}")
cat(makeItNiceR("foo bar is nice"))
@

\paragraph{Outside of chunk:} ~\\

\Sexpr{myoutput} \\

Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX. \\

\Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
\end{document}



来源:https://stackoverflow.com/questions/32327697/how-to-layout-character-value-within-r-chunk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!