How to include output of help() in sweave pdf - r

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

Related

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 debug a Rsweave

I have an rsweave file that I run almost twice a week. Last time I used it a change a couple of things and when I run it to compile to pdf I got the following errors:
The pdf compiles complitly, and the only thing I notice that the error did is that the the pdf output has a extra page (the first one) all blank. I don't know how to make a reproducible example of the errors because I don't know whats the cause of it. But any way I just want to know generally how to debug a rsweave file when getting latex error like the ones in the picture
You don't say how you are running Sweave, but that looks like RStudio. To debug something like this, just run Sweave explicitly in the R console, e.g. if your input file is source.Rnw, run
Sweave('source.Rnw')
This will produce source.tex. Open that file in a text editor and look at the start of it. You will see that \Schunk is used on line 27, but \begin{document} doesn't occur until sometime later.
My guess is that you added some text or a code chunk to the header. All text belongs after \begin{document}.
Edited to add: It turns out from the comments below that you were using print(...) in a code chunk before \begin{document}. In Sweave, print output goes into the document. If you want a message to show up in the console log but not the document, use message("some text"). You'll also need to suppress the echoing of the command if you want to do this in the document header. For example,
<<echo=FALSE,results=hide>>=
message("Started at ", Sys.time())
#
will result in something like this in your console log:
1 : keep.source term hide (Untitled.Rnw:6)
Started at 2017-09-27 08:28:33
and nothing in the document.

How to extract all code chunks from a Rnw Sweave file?

I received a .Rnw file that gives errors when trying to build the package it belongs to. Problem is, when checking the package using the tools in RStudio, I get no useful error information whatsoever. So I need to figure out first on what code line the error occurs.
In order to figure this out, I wrote this 5-minute hack to get all code chunks in a separate file. I have the feeling though I'm missing something. What is the clean way of extracting all code in an Rnw file just like you run a script file? Is there a function to either extract all, or run all in such a way you can find out at which line the error occurs?
My hack:
ExtractChunks <- function(file.in,file.out,...){
isRnw <- grepl(".Rnw$",file.in)
if(!isRnw) stop("file.in should be an Rnw file")
thelines <- readLines(file.in)
startid <- grep("^[^%].+>>=$",thelines)
nocode <- grep("^<<",thelines[startid+1]) # when using labels.
codestart <- startid[-nocode]
out <- sapply(codestart,function(i){
tmp <- thelines[-seq_len(i)]
endid <- grep("^#",tmp)[1] # take into account trailing spaces / comments
c("# Chunk",tmp[seq_len(endid-1)])
})
writeLines(unlist(out),file.out)
}
The two strategies are Stangle (for a Sweave variant) and purl for a knitr variant. My impression for .Rnw files is that they are more or less equivalent, but purl should work for other types of files, as well.
Some simple examples:
f <- 'somefile.Rnw'
knitr::purl(f)
Stangle(f)
Either way you can then run the created code file using source.
Note: This post describes an chunk option for knitr to selectively purl chunks, which may be helpful, too.

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