Sweave - using a variable from Latex into code chunks - r

I need to use variable (ie. an argument of a custom command) from latex into a R inline code chunk. See, for instance :
\newcommand{\textvar}[1]{
\textbf{
\Sexpr{
# Here, I would like to use the one argument of my \textvar command to do somthing in R
}
}
}
Of course, I can't just add #1 like in pure Tex, it would just comment the line in R.

You can't do that because of the order in which things are run. First Sweave() processes the .Rnw file to produce a .tex file, then LaTeX processes the .tex file to produce output. Sweave (and hence R) knows nothing about LaTeX macro processing.
What you could do is write an R function that outputs the LaTeX you want, e.g. something like
textvar <- function(x) {
paste0("\\textbf{", x, "}")
}
and then insert this as an inline code chunk
\Sexpr{textvar(x)}
which will expand to the LaTeX code you want your \textvar macro to insert.

Related

Print latex code to .tex file using cat() or print()

I want to print a chunk of latex code using R. I've previously used cat() to do this, my problem is that it quickly becomes a cumbersome task when I have a large body of text including tables written in latex as I have to include additional backslashes in R. i.e., if I want a tex-file with the following:
\begin{document}
I would need to write something like
cat("\\begin{document}", file= test.tex, append = T, sep="\n")
in R.
I've also tried:
sink("test.tex")
print("\begin{document}", quote = F)
sink()
which almost gives me the desired result except for the fact that it prints row numbers in front of the text, more specifically it prints:
[1] \begin{document}
Is there a way to write plain latex code in R and get it to work properly without adding additional backslashes or row numbers?
I know there are more sophisticated solutions using sweave, knitr, Rmarkdown but would prefer to a solution using print/writeLines/cat, etc.
If you are pasting text into the console or piping a file into R from the command line, you can use something like this:
latex <- scan(what = character())
\begin{document}
\end{document}
writeLines(latex, "test.tex")
where the blank line tells scan() to stop reading. However, if you put those lines in a file and source() it, you'll get an error, because it's not all syntactically correct R code.
You're definitely better off to use knitr with .Rnw input.

Define commands for frequently used text in knitr

Is there a way to define a command that can be used as a short cut for frequently used text or html commands in knitr when compiling to html?
I use knitr to compile an rmkardown file (.Rmd) and the output is a html file (i.e., I press Knit HTML in RStudio).
To be more specific, let me add an example: I want to separate the percent sign by a hair space from the number before, which I achieve by typing, e.g., 5 %. It would be very convenient, if I could define a command, let's say \perc, that I can use instead, such that 5\perc would be equivalent to 5 %.
Is this at all possible and if yes, how can it be done?
You can define an R function and then call it inline. For example:
```{r}
perc <- function(){
" %"
}
```
This is inline r code 5`r perc()`
I think you could also use it in chunks where the result would be 'asis'.

How to insert a number from R to LaTeX?

I´m trying to insert a number directly from R into a LaTeX file. I have only been able to do it as a table and that doesn´t allow me to put it in the middle of a sentence.
I would like the output to look like this:
"The final number is [number directly from R]"
What should I do?
If you use the Sweave or knitr (assuming .Rnw file), use \Sexpr{foo}. Then run the file through R + Sweave or R + knitr and you'll have a LaTeX source with the value of foo inserted in place of \Sexpr{foo}.
Basically you need to markup your LaTeX source appropriately, run it through a system using R to identify the things you want to replace and insert the actual data into the source file, and output a LaTeX source which you can then compile.
There are other systems besides Sweave and Knitr so find a system you like that suits your workflows. For example, there is brew.

Hmisc tilde rowname

I am trying to group row names in a R data frame for typesetting with the Hmisc latex() function. Problem is that latex() adds two tilde characters before each row name, and these show up in my document.
How can I either remove these characters or have them not show up?
Example:
test.df <- data.frame(row.names=letters[1:4], col1=1:4, col2=4:1, col3=4:7)
latex(test.df, file="", n.rgroup=c(2,2), rgroup=c("First","Second"))
Edit:
The latex function occurs inside a knitr chunk. The resulting .Rnw file is compiled through the knit2pdf function, which uses pdfLatex by default, I think. All other tables/figures in the document compile fine, without any residual LaTex syntax showing up.
They will not show up if you use latex with a TeX processor:
test.df <- data.frame(row.names=letters[1:4], col1=1:4, col2=4:1, col3=4:7)
latex(test.df, file="test", n.rgroup=c(2,2), rgroup=c("First","Second"))
If you want to "capture" the text that is "printed" to the screen and remove the double tildes with sub then you probably need to use capture.output, because it appears that latex is not returning a value but is acting more like the cat function which has output to the screen as a side-effect:
out <- sub("^~~", "", capture.output(
latex(test.df, file="",
n.rgroup=c(2,2), rgroup=c("First","Second"))))
You could then use writeLines or cat with a file argument to send that text to a destination. I suppose it is possible that you could just put the sub call inline without diverting the results to a named object. That will depend on exactly how your are processing this text.
If you don't want to use LaTeX then i suggest either the ascii package that has pretty advanced options that do a nice raw text output (it also has the rgroup & n.rgroup options for grouping row names). If you are interested in getting the tables into a Word document (or just HTML) i suggest Markdown with my htmlTable function - the arguments are based upon the Hmisc latex arguments as I needed a replacement when I was switching to Markdown, thus all you need to do is change the function name to htmlTable after loading my package.

How can I save text to a file in R?

I have a R function which can generate the LaTeX code (the output is the LaTex code) by using cat(), while now I want to save these LaTeX code, but I don't know which function can save these LaTeX code...
I like to use the sink() function:
latex.code <- function(){
cat("\\begin{align}\n")
cat("[X'X]^{-1}X'y\n")
cat("\\end{align}\n")
}
sink(file='ols.txt')
latex.code()
sink()
Edit: Obviously, you can choose the file path where the file will be saved by changing the sink argument such as: sink(file='c:/Users/Eva/Desktop/ols.txt'), or sink(file='~/ols.txt')
Assuming your R function returns a character string of LaTeX code (your question would be much improved if you made it more concrete, with some specific examples), you can output something like that to a file using the cat() function, and specifying a file using the file= argument. You can read about it via ?cat.
If it happens that you have your output in a character vector (i.e. you are using something like cat(<something>) to have it written to the console), you can use writeLines function, like this:
writeLines(<something>,"filename.txt")
However the best way to make a LaTeX file in R is to use either Sweave or make a brew template.

Resources