Conditional output of dynamic text in a LaTeX knitr document - r

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.

Related

How to turn off rounding when I knit to pdf or word doc?

guys so I am using a tidy model function to get the output of the RMSE and RSQ. I'm using the function as so and get the right output with the correct decimal places. My issue is when I knit to pdf it seems to round off my answer to the nearest 1 decimal place. Does anyone know how I can turn this off?
R code results.
When I knit to pdf.
You can use the pillar.sigfig option to choose the number of significant digits a tibble prints (see ?tibble::formatting). Then you can set that option for a single code chunk using R.options.
This gives:
```{r R.options=list(pillar.sigfig = 10)}
tibble::tibble(x=runif(5),
y = runif(5))
```

highlight all inline \Sexpr{} outputs in the generated pdf

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))})

inline Latex code inside knitr R block

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 :
How would I use inline latex code for the output from line 8, in case I wanted to color, bold etc. that text.
Can one eliminate the grey box that appears when we use the cat or print command.
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!

How to layout character value within R chunk

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}

Special characters in R code output not printed into PDF (though graphical stuff works well)

WORKING EXAMPLE IN THE END
I want to use knitr to have R code inside LaTeX document, but it doesn't print correctly into PDF when there are non-ascii characters. The situation is similar as in the question user unikum asked in GitHub, but the solution given there helped only partially in my case.
Ideally the printed line(s) would be inside normal text and have suitable LaTeX formatting, especially in cases where the result is simply one line. I have some uses in my mind where example sentences in a research paper would be automatically taken from the data files.
I wrote Rnw file in RStudio (0.98.945), I used XeLaTex for typesetting. I created PDF simply by clicking Compile PDF button in RStudio. I have MacBook Pro with Mavericks. Please let me know if some additional information is needed. I can also switch to other programs (like TeXShop etc.) if that helps.
I'm still learning all these tools, R, knitr and LaTeX, so I apologise if I have missed any obvious solution or misuse some terminology. I tried to combine different solutions from similar problems, like this about Polish characters or this about Hebrew. There are many people writing about bit similar problems, but I still have problems to get it together. I guess this is encoding issue.
Here is my LaTeX preamble:
\documentclass{article}
\usepackage{hyperref}
\usepackage {fontspec}
\setromanfont{Charis SIL}
<<setup, include=FALSE>>=
options(device = function(file, width = 7, height = 7, ...) {
cairo_pdf(tempfile(), width = width, height = height, ...)
})
#
In normal text I can have any possible unicode characters and they appear all correctly in the pdf: мичаа лыддьыны позьӧ, me t'š́uži š́urs e̮kmis-š́o dasɛ͔d voɛ͔ š́ent'a·b das-e̮kmi͔sɛ͔d lunɛ.
I assume this has something to do with encoding.
In my example I scan to R the text file (test.txt) that contains following 10 lines, they are just random word forms in Finnish and Komi:
Серафимлӧн
тшӧктісны
налысь
sivulla
ёрт
дугдыны
sivu-ovi
Esko
Серафим
akkuna
The following code prints the result correctly:
<<test1, echo=FALSE, comment=NA>>=
test <- scan(file="test.txt", what="char", sep="\n")
wordlat <- grep("sivu", test, value=T)
print(wordlat)
#
The result is this:
[1] "sivulla" "sivu-ovi"
But this doesn't:
<<test2, echo=FALSE, comment=NA>>=
test <- scan(file="test.txt", what="char", sep="\n")
wordcyr <- grep("Серафим", test, value=T)
print(wordcyr)
#
What comes out is:
[1] "" ""
I modified marginally the example which was posted to GitHub. I just wanted to have both latin and cyrillic in the labels. As one could expect, adding cairo_pdf to the beginning helped:
<<pie-plot, dev='cairo_pdf'>>=
x <- gl(3, 4, 50, labels=c("Pretty easy!", "Дзик гӧгӧрвотӧм!", "Кувны позьӧ :("))
pie(table(x), main="How difficult is this question")
#
The pie comes out perfectly, but there is clearly still something wrong, because the code above it says:
x<-gl(3,4,50,labels=c("Pretty easy!"," !"," :("))pie(table(x),main="How difficult is this question")
WORKING EXAMPLE:
I see now that I should had paid more attention to give a piece of code one can just copy and run. My apologies for that. So the example below is the same as in my original post, but it can be copied into RStudio and it should make one page PDF which has the problems I described. Sorry for repeating the same, but I though it maybe makes my question more unclear if I start to edit the whole post.
\documentclass{article}
\usepackage {fontspec}
\setromanfont{Charis SIL}
\begin{document}
<<setup, include=FALSE>>=
options(device = function(file, width = 7, height = 7, ...) {
cairo_pdf(tempfile(), width = width, height = height, ...)
})
#
So this comes out fine.
<<test1, echo=FALSE, comment=NA>>=
test1 <- c("Серафимлӧн", "тшӧктісны", "налысь", "sivulla", "ёрт", "дугдыны", "sivu-ovi", "Esko", "Серафим", "akkuna")
wordlat <- grep("sivu", test1, value=T)
print(wordlat)
#
But for some reason this doesn't. How to make it show characters correctly, that's the whole question I posted about.
<<test2, echo=FALSE, comment=NA>>=
test2 <- c("Серафимлӧн", "тшӧктісны", "налысь", "sivulla", "ёрт", "дугдыны", "sivu-ovi", "Esko", "Серафим", "akkuna")
wordcyr <- grep("Сера", test2, value=T)
print(wordcyr)
#
The graphical things come out fine with cairo-package, but only within the graph itself:
<<pie-plot, dev='cairo_pdf'>>=
x <- gl(3, 4, 50, labels=c("Pretty easy!", "Дзик гӧгӧрвотӧм!", "Кувны позьӧ :("))
pie(table(x), main="How difficult is this question")
#
The code above the graph in the PDF has the same problem as in earlier example which contained cyrillic:
c("Pretty easy!"," !"," :("))
\end{document}
Thanks for help!

Resources