How can I save text to a file in R? - 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.

Related

Sweave - using a variable from Latex into code chunks

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.

How to make the output recognizable in Sweave

I am using Sweave to be able to combine LaTeX and R. I find useful to be able to remove the prefix ">" and "+" from the input writing options(prompt=" ", continue=" ") .
I would like to find a way to make the output recognizable from the input, for instance adding a prefix "#" to the output (as it happens with R Markdown).
Any help?
I'm not sure if you know that knitr can also compile .Rnw documents (Sweave), in addition to .Rmd (R Markdown). You just pass the file path to knitr::knit(), e.g.,
knitr::knit('test.Rnw')
And you will get the .tex output file. If you want to get the PDF output directly, you may call:
knitr::knit2pdf('test.Rnw')
By default, knitr doesn't add the prompt character > or + to your code in the output.

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 to include output of help() in sweave pdf

I would like to include function documentation from the help file in a sweave document. I tried the following sweave block
<<>>=
?lm
#
but I get error messages when calling Sweave on the Rnw file. How can I include the entire help message in the document?
The key to this is really figuring out how to get the information you desire as a character string.
help("lm") opens up the help file for the relevant function, but not in the console.
utils:::.getHelpFile gives you the Rd version of that file.
From there, you can use tools:::Rd2txt to convert it to text...
Which can be "captured" using capture.output.
Those are essentially the steps contained in the first few lines of helpExtract from my "SOfun" package. That function, however, captures just the requested section.
Instead, if you can settle for just the text, you can do something along the lines of:
gsub("_\b", "",
capture.output(tools:::Rd2txt(
utils:::.getHelpFile(utils::help("lm")))))

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