Hmisc tilde rowname - r

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.

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.

Displaying dataframes in R Markdown

I can't find a method to remove the hash marks and row numbers from dataframes outputted to a word document in R markdown. I'd like to be able to present only the data without those features
The knitr website and specifically the page on Chunk options suggests the use of a separate chunk (before your want to display a data.frame in this manner) to change the default for the chunk option comment, perhaps like this:
```{r global_options}
opts_chunk$set(comment = NA) # default value is '##'
```
to disable the inserting of comment characters on output. Realize that this setting of the comment option is applicable to all chunks that follow this chunk; this chunk itself will not be affected by it.
This does give the textual representation of the data.frame (as if it were on the terminal), and not a more refined representation. I second #PierreLafortune's suggestion to look at knitr::kable.
Check out the sjPlot package and specifically the view_df function

remove \begin{tabular} from Stargazer .tex output

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.

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