Write latex equation inside knitr chunks - r

I am trying to write a equation inside a chunk. I need to use '\sum' but R does not accept it. I got the error:
'\s' is an unrecognized escape in character string
I also tried some packages without success.
How can I bay pass this escape character?
Here is the example:
\documentclass{article}
\begin{document}
<<results='asis',echo=FALSE>>=
#library(lazyWeave)
#library(hwriterPlus)
#hwriteLatex(as.latex("\bar{R}_{i}=\frac{\sum_{t=1}^{T}{R_{i,t}}}{8}"))
#
cat('\bar{R}_{i}=\frac{\sum_{t=1}^{T}{R_{i,t}}}{8}')
#cat("$$","\bar{R}_{i}=\frac{\sum_{t=1}^{T}{R_{i,t}}}{8}","$$",sep="")
cat("Typically we want our paragraphs to be left
justified. This is often what we expect to see when reading.")
#
\end{document}
Edit. I read some similar examples but no one involved escape characters.

You need to double the escape character.
> cat('\\bar{R}_{i}=\\frac{\\sum_{t=1}^{T}{R_{i,t}}}{8}')
\bar{R}_{i}=\frac{\sum_{t=1}^{T}{R_{i,t}}}{8}>

Related

Less space between letters and units in rmarkdown (pdf and docx output)

I cannot find any information about spacing between letters in R Markdown. All I found only were questions about vertical spacing. I basically have two issues:
In LaTeX I usually use the siunitx package to correctly typeset numbers and units. I can of course use this in R Markdown as well if I load the package with \usepackage{siunitx}. But this does not output to the docx format, only to pdf. That brings me to my other question...
So I tried using different spaces of LaTeX to display numbers and their units with at least less space, e.g. writing 40\,m^2 to display 40 m² (in LaTeX I would use \SI{40}{\square\meter}). However, apparently R Markdown does not handle the \, nor \; at all, not even in the pdf output.
Question: What is the correct way to add smaller spaces between letters in R Markdown? (irrespective of output format!) How do I replace the \, command?
And: Is there a way to handle units nicely using R Markdown? I have found this question on the R units package, and I could live with it. That is, if I want to write hardcoded numbers like 40 m² I would have to use something like`r format(set_units(40, m2))`,right?.
Have you tried adding thin spaces using Unicode chars? For example, this page http://jkorpela.fi/chars/spaces.html suggests that "\u2009" and "\u200A" should display as thin spaces.
When I try this with a PDF document (using latex_engine: xelatex to handle Unicode), this is what I see:
It also appears to work with HTML and Word output.
Edited to add:
To be clear, this needs to go through R. If you want it inline, use code like this:
This is standard spacing: 40 m²,
this is narrow `r knitr::asis_output("40\u2009m²")` spacing.
This produces this output in PDF:

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.

How can I write a degree symbol in RMarkdown 2?

I'm writing some code with descriptions using Rmarkdown 2 and knit PDF.
I've been trying many method to write a degree symbol inline:
Latex package: siunitx's \ang
Latex package: textcomp's \textdegree
Latex: \circ
And many possible RMarkdown symbols, such as:
$$ \textdegree $$ or $\textdegree$
But nothing is working. Is there a way to write a degree symbol in RMarkdown 2 and convert it do PDF?
EDIT (18 AUGUST 2014):
Ok, I found out where is the problem. If you use \circ in normal sentence or first-level list it is ok. But when I try to use \circ in second-level list - it's not working.
The problem was with RMarkdown converting nested lists. On this page http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html you can find sentence:
The nested list must be indented four spaces or one tab
Although, using the tab could be a problem. When using four spaces - it works:
* Let's turn this round 360$^\circ$
+ Let's turn this round 360$^\circ$
Using \circ works for me, RStudio, knit to pdf:
Let's turn this round 360$^\circ$
You can use plotmath's degree, e.g.
plot(1, xlab=expression(4*degree))

Excess backslashes in stargazer latex output

I get a weird result when trying to output my regression results into latex tables using the stargazer package in R: when I simply do
stargazer(linear.1,linear.2)
I get a perfectly fine latex table displayed in the R console that I can then copy and paste into my latex editor. However, when I use
table<-stargazer(linear.1,linear.2)
the character object 'table' does not have the same latex output that one would expect given the results of the first line of code, but rather the same latex code as before with an additional backslash before every backslash in the original latex code, e.g. instead of \begin{document} I get \\begin{document}, instead of two backslashes for a line break I get three backslashes etc.
Any idea what is causing this behavior and how I could fix it?
Thanks!
Perfectly normal behavior, as backslashes in R string require an escape character that just happens to be... a baskslash!

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.

Resources