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.
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}
Related
I have the following RMarkdown Document (also here as a gist)
results in this
I would like to use the function fun() to create a proper table as from the first code chunk.
I thought that format = "markdown and results = "asis" should do the job, but apparently not.
What Am I missing here?
I have an R vector of filepaths for pdf figures I would like to put into my knitr document and knit to html. I see that I can get a single pdf to be included with
knitr::include_graphics(filepaths[1])
My filepaths vector is long and changes size between document compilations. Is there a method of including them all in one go. I had imagined this would work.
for(i in filepaths){knitr::include_graphics(i)}
Had also tried:
for(i in filepaths){ print("![](", filepaths[i], ")" ) }
knitr::include_graphics() is vectorized, so the answer is simply:
knitr::include_graphics(filepaths)
Your first solution does not work because knitr::include_graphics() needs to be the top-level expression. Your second solution does not work because you should use cat() instead of print(), and the chunk option results='asis'.
There are several advantages of using include_graphics() over cat() + results='asis'.
Try using cat instead of include_graphics. For example:
for(i in 1:length(filepaths) {
cat("![](", filepaths[i], ")")
}
This is general Markdown syntax: ![NAME](PATH).
With this solution you will need to use results = "asis" in chunk header.
I'd like to print a few sentences in a knitr LaTeX doc (.Rnw), but only if some data exists. Those sentences are mostly text, but with some R.
Example:
A chi-squared test of your observed sizes has a p-value of
\Sexpr{format(calculated_chisq$p.value,digits=3,scientific=F)}.
A p-value below 0.05 means you should be concerned that your
groups are broken. The lower the p-value, the more worried you
should be.
I tried a chunk with results='asis', but I think the chunk is interpreted as R.
I tried print() and paste() with R. It's ugly, but it works. However, it puts extra text in that seems to correspond to the R prompt.
Is there a nice way to do this?
This is related, but different. This is the same, but unanswered.
This question is closely related to that question, but not duplicate I think: The accepted answer there translates into an ugly \Sexp monster with a condition inside. The code will be neither nice to read nor to write.
My own answer there is also not applicable because 1) the asis engine does not allow for dynamic elements in the text and 2) because output from the asis gets a gray background color in RNW documents.
I suggest the following solution:
\documentclass{article}
\begin{document}
<<>>=
x <- rnorm(1)
#
The value of $x$ is \Sexpr{x}.
<<echo=FALSE, results = "asis">>=
pattern <- "This will only be displayed if $x$ is positive. The value of $x$ is %.2f."
if (x > 0) cat(sprintf(pattern, x))
#
\end{document}
The conditional output is easy to read and write (pattern) and the dynamic elements are inserted via sprintf.
I am using knitr for a report wherein I have a lot of inline output text, mostly numeric values, using \Sexpr{}. I want to highlight All these inline outputs in my generated pdf.
Example code:
\documentclass[12pt]{article}
\begin{document}
<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
#
There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.
\end{document}
Hence, in the output all the number should be highlighted, i.e. with a shaded background (similar to using with \hl{} with the \usepackage{soul}).
It seems to me that the solution would use one of the inline output hooks. Another possibility might be to write a LaTeX function which search all the \Sexpr{...} expressions in the entire document and highlights them in the generated pdf. I am still learning and can not figure out how to implement these.
Thanks for any help or hints.
Note: The knitr page by yihui talks about manipulation of the numeric value (scientific notation, digits after decimal points) which I have got covered.
The output hook inline can be used to style output from \Sexpr{}. This is as simple as
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", x)})
Just define an arbitrary function that takes an argument x and returns the string to be printed. In this example I used \textbf to make the output bold, but this can be extended to any LaTeX commands.
In this answer, Yihui suggests an improvement that still takes the default inline hook into account. This ensures rounding as usually performed by the default hook:
hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", hook_inline(x))})
I'm working on a document in R, with knitr to pdflatex and am using the extended version of toLatex from memisc.
When I'm producing a table with cut intervals however, the square brackets are not sanitised and the pdflatex job errors because of the existence of [.
I tried putting sanitize=TRUE in the knitr chunk code, but this only works for tikz.
Previously, I have used gsub and replaced the string in the R object itself which is rather inelegant. I'm hoping someone could point me in the direction of a nuance of memisc or knitr that I'm missing or another function/method that would easily handle latex special characters.
Example
library("memisc")
library("Hmisc")
example<-data.frame(cbind(x=1:100,y=1:100))
example$x<-cut2(example$x,m=20)
toLatex(example)
UPDATE
Searching SO I found a post about applying latexTranslate with apply function, but this requires characters so I would have to unclass from factor to character.
I found another SO post that identifies the knitr:::escape_latex function however, the chunk then outputs the stuff as markup instead of translating it (using results='asis') or produces an R style table inside a code block (using results='markup'). I tried configuring it as a hook function in my parent document and it had the effect of outputting all the document contents as markup. This is a brand new area for me so I probably implemented it incorrectly.
<<setup,include=FALSE>>=
hook_inline = knit_hooks$get('inline')
knit_hooks$set(inline = function(x) {
if (is.character(x)) x = knitr:::escape_latex(x)
hook_inline(x)
})
#
...
<<tab-example,echo=FALSE,cache=TRUE,results='asis',sanitize=TRUE,inline=TRUE>>=
library("Hmisc")
library("memisc")
example<-data.frame(cbind(x=1:100,y=1:100))
example$x<-cut2(example$x,m=20)
toLatex(example)
#
According to #yihui this is the wrong way to go
UPDATE 2
I have created a gsub wrapper which will escape percentages etc, however the [ symbol still pushes latex into maths mode and errors.
Courtesy of folks on the tex SE, a [ directly after a line break(\\) is considered an entry into math-mode. It is very simple to prevent this behaviour by adding {} into the output just before a [. My function looks like:
escapedLatex<-function (df = NULL)
{
require("memisc")
gsub(gsub(x = toLatex(df, show.xvar = TRUE), pattern = "%",
replacement = "\\%", fixed = TRUE), pattern = "[", replacement = "{}[",
fixed = TRUE)
}
I'd be very happy to see any alternative, more elegant solutions around and will leave it open for a few days.