remove \begin{tabular} from Stargazer .tex output - r

Is there a simple way to automatically remove the
\begin{tabular}{#{\extracolsep{5pt}}lc}
and
\end{tabular}
lines at the beginning and end of a Stargazer LaTeX output?
Indeed, I just need the inside LaTeX code and removing those lines manually from the TeX file generated by stargazer is a complete loss of time...

Each of the functions defined to create the LaTeX output in stargazer are defined within the (internal) wrapper function .stargazer.wrap. As such, it's not that easy to update the components automatically. You'll either have to make a copy of the package that you maintain locally, or edit the .stargazer.wrap function every time you load the package.
Here's how to do the latter, following the guidelines from How do I override a non-visible function in the package namespace? (managing your own copy would entail something similar):
Load stargazer:
> library(stargazer)
Edit the .stargazer.wrap function inside the stargazer namespace/package:
> fixInNamespace(".stargazer.wrap", pos="package:stargazer")
Find and remove at least rows 4206-4207 from the .data.frame.table.header function:
These two lines are used to print the tabular header.
Find and remove at least row 3385 in the .publish.table function:
This line prints \end{tabular} (plus a line break).

Having the same issue, I ended up just adding some lines to my R code after having created the table with stargazer:
filename <- paste0("./my/path/", dplyr::last(list.files("./my/path/"))) # always loads the last file
lines <- readLines(filename) # read file
lines[1:4] <- "" # I wanted to replace the first four lines
lines[length(lines)] <- "" # as well as the last line
Hope this helps.

Related

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

R: Capture output of regression in string [duplicate]

I have multiple regressions in an R script and want to append the regression summaries to a single text file output. I know I can use the following code to do this for one regression summary, but how would I do this for multiple?
rpt1 <- summary(fit)
capture.output(rpt1, file = "results.txt")
I would prefer not to have to use this multiple times in the same script (for rpt1, rpt2, etc.), and thus have separate text files for each result. I'm sure this is easy, but I'm still learning the R ropes. Any ideas?
You can store the result as a list and then use the capture.output
fit1<-lm(mpg~cyl,data=mtcars)
fit2<-lm(mpg~cyl+disp,data=mtcars)
myresult<-list(fit1,fit2)
capture.output(myresult, file = "results.txt")
If you want multiple output sent to a file then look at the sink function, it will redirect all output to a file until you call sink again. The capture.output function actually uses sink.
You might also be interested in the txtStart function (and friends) in the TeachingDemos package which will also include the commands interspersed with the output and gives a few more options for output formatting.
Eventually you will probably want to investigate the knitr package for ways of running a set of commands in a batch and nicely capturing all the output together nicely formatted (and documented).

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.

Print or capturing multiple objects in R

I have multiple regressions in an R script and want to append the regression summaries to a single text file output. I know I can use the following code to do this for one regression summary, but how would I do this for multiple?
rpt1 <- summary(fit)
capture.output(rpt1, file = "results.txt")
I would prefer not to have to use this multiple times in the same script (for rpt1, rpt2, etc.), and thus have separate text files for each result. I'm sure this is easy, but I'm still learning the R ropes. Any ideas?
You can store the result as a list and then use the capture.output
fit1<-lm(mpg~cyl,data=mtcars)
fit2<-lm(mpg~cyl+disp,data=mtcars)
myresult<-list(fit1,fit2)
capture.output(myresult, file = "results.txt")
If you want multiple output sent to a file then look at the sink function, it will redirect all output to a file until you call sink again. The capture.output function actually uses sink.
You might also be interested in the txtStart function (and friends) in the TeachingDemos package which will also include the commands interspersed with the output and gives a few more options for output formatting.
Eventually you will probably want to investigate the knitr package for ways of running a set of commands in a batch and nicely capturing all the output together nicely formatted (and documented).

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