I Imagine this pretty simple, but I am very new to R and stargazer so I am not sure how to do this.
I have a code block (seen below):
ses <- diag(vcovHC(model))
stargazer(model,
type='latex',
header = F,
se = ses,
title="")
I want to convert this output into a Latex Table. I've tried playing with markdown but I can't seem to get anything to work.
Can anyone advise on how to do this? I've tried using latex editors but I can't source the data into that.
Thank you!
Output is text file with latex code. You can use it in latex editor with appropriate modifications.
Hope I have answered your query correctly.
sink("output.txt")
stargazer(mod1,se = robustse_mod_1,type = "latex")
sink()
Related
It's me again, quite the beginner at R but somehow fumbling my way through it for my thesis. I've run a bunch of regressions and made them into tables using Stargazer. Now I need to share all these results (the glm models/their summaries/the coefficients and confidence intervals and the stargazer tables ... basically everything in my console) with a friend of mine to discuss, but I figure there's got to be a more efficient way to do this than 1) screenshot-ing the hell out of my console or 2) copy and pasting the console and thus botching the formatting. Does anyone have any advice for this?
Some of my code (the rest is just variations on the same stuff) is below in case that's helpful!
Mod4 <- glm(`HC Annual Total` ~ `state population`
+ Year + `Trump Presidency`, data = thesis.data, family = poisson())
summary(Mod4)
#pulling the coefs out, then add exp for what reason I don't remember
exp(coef(Mod4))
#finding the confidence intervals
exp(confint(Mod4))
#Using stargazer to turn Mod4 into a cleaner table
library(stargazer)
stargazer(Mod4, type="text", dep.var.labels = c("Hate Crimes"),
covariate.labels = c("State Population", "Year", "Trump Presidency"),
out = "models.txt")
When you need it fast and without art, you could send console output to a simple text file using sink.
sink(file="./my_code.txt") ## open sink connection
timestamp()
(s <- summary(fit <- lm(mpg ~ hp, mtcars)))
cat('\n##', strrep('~', 77), '\n')
texreg::screenreg(fit, override.se=s$coe[,3], override.pvalues=s$coe[,4])
cat('\n# Note:
We could report t-values
instead of SEs\n')
cat('\n##', strrep('~', 77), '\n')
cat('\nCheers!\nJ')
sink() ## close it!
file.show("./my_code.txt") ## look at it
Note, that you can easily create a mess with unclosed sinks and no output is shown on the console. Try closeAllConnections() in this case or perhaps milder solutions. Also consider rmarkdown as suggested in comments.
savehistory() is your friend:
savehistory(file = "my-code.txt")
You can then edit the code at will.
Or, in RStudio, you can use the history pane and copy and paste relevant bits to a text file.
If a full rmarkdown document is overkill, you could try using knitr::spin() to compile your code.
Lastly:
In future, always write scripts.
Reproducibility is best thought of at the start of a project, not as an add-on at the end. It's much easier to run a carefully-written script at the console, than it is to turn your meandering console input into a useful script. A good workflow is to try a few things at the console, then once you know what you are doing, add a line to your script.
I think reprex is an intermediate solution between rmarkdown and sink. At first, make sure your R script can be executed without any errors. Then use the following code:
library(reprex)
r.file <- "path/to/Rscript/test.R" ## path to your R script file
reprex(input = r.file, outfile = NA)
There will be four files created in the directory of your R script file, i.e.
test_reprex.R
test_reprex.html
test_reprex.md
test_reprex.utf8.md
The html and md files contain codes in your original R script and their output. You can share with someone and they can see the output without running any codes.
The html file looks like:
I have the following code in my Rmd file:
library(randomForestSRC)
library(ggRandomForests)
rf_all <- rfsrc(Y ~ ., data=df, block.size=1, ntree=100, importance=TRUE)
plot(gg_vimp(vimp.rfsrc(rf_all))) + theme(legend.position = "none")
rf_select <- var.select.rfsrc(rf_all)
pander(rf_select$varselect)
confmat <- confusionMatrix (rf_all$class.oob, data$Enddiagnosegruppe)
pander(confmat$table)
I'm trying to create an HTML report, but I cannot for the life of me figure out what chunk options to use such that:
The output of the rfsrc functions is suppressed.
All the plots appear.
The calls to pander yield properly formatted output.
I have tried pretty much all combinations of chunk options for message, warnings, error, as well as wrapping parts of my code in invisible(), capture.output(), as well as playing around with panderOptions('knitr.auto.asis', FALSE). Nothing seems to work, either the messages are not suppressed, pander tables look weird, empty section headers appear out of nowhere (I'm guessing "##" is inserted somewhere), no luck. I feel like I'm missing the forest for the trees here. Not to mention that this code is supposed to be wrapped in a loop that generates different formulae. Any suggestions on how to get this to work?
Using the following works:
rf_select <- var.select.rfsrc(rf_all, verbose=FALSE)
cat("\n")
pander(rf_select$varselect)
The problem is that var.select.rfsrc() uses cat() instead of message(), and somehow adding a newline is necessary since otherwise the first pander table is run together with the previous line in the markdown file.
How do I go about removing the output shown in the picture below after I use read_excel to import the data in r markdown. Basically I don't want there to be any output after this function. Please see attached image.
bdims <- read_excel("bdims.xlsx")
head(bdims)
You can set results = 'hide'. So if eg. for standard rmarkdown. This will stop the output from showing. Read on the cheat sheet how to use other settings such as echo and eval
{results = 'hide'}
bdims <- read_excel("bdims.xlsx")
or with roxygen document for rendering rmarkdown,
#+ results = 'hide'
bdims <- read_excel("bdims.xlsx")
I was wondering if there is a way to have HTML output with syntax coloring of a line of code in R. It should do something like:
HTMLoutput <- HTMLsysntaxColoring("a <- paste('hello,', 'world')")
The output should be readable HTML code that shows the line with R syntax coloring.
Knit does something like this for a whole document, but I would like to have it for a single command line.
The reason why I am doing this is that I am developing a package to do profiling in R (it is in CRAN, GUIProfiler). It builds an HTML report that includes the profiled code shadowed for the places that take more time. Unfortunately, I used Nozzle.R1 instead of knitr to generate the report. Nozzle.R1 seems to be discontinued and is not able to display the code with syntax coloring. knitr is actively updated and does have syntax coloring.
Instead of rebuild the package from scratch using knitr (perhaps is what I will do in the future), I was trying "to patch it" using knitr to generate the syntax coloring and pasting it into the Nozzle.R1 package.
This ought to do it, though I'm curious as to what you're really actually looking for.
html_syntax_coloring <- function(r_code) {
require(knitr)
r_code <- paste0("```{r eval=FALSE}\n", paste0(r_code, collapse="\n"), "\n```")
tmp_in <- tempfile(fileext=".Rmd")
cat(r_code, file=tmp_in)
tmp_out <- tempfile(fileext=".html")
on.exit(unlink(tmp_out))
knit2html(tmp_in, tmp_out, quiet=TRUE)
paste0(readLines(tmp_out), collapse="\n")
}
html_syntax_coloring("a <- paste('hello,', 'world')")
Is it possible to include R documentation in knitr output? When using stock datasets, it would be nice to just include the builtin documentation without having to copy and paste it in. The problem appears to be that ? works by side effect and so there is no "result" in a meaningful sense. For example,
```{r}
?mtcars
```
has no output that is trapped by knitr.
Using help(...,help_type) instead of ? doesn't help either. I've tried:
```{r, results='markup'}
help(mtcars, help_type="text")
```
and
```{r, results='asis'}
help(mtcars, type="html")
```
with the same result. (In the latter case, knitr did trap the output ## starting httpd help server ... done, which is basically just a message about the side effect.)
In other words, is there a way to extract R help in plain text or HTML?
To answer your specific question, "Is there a way to extract R help in plain text or HTML?", the answer would be to use a combination of Rd2HTML or Rd2txt from the "tools" package, with a little bit of help from .getHelpFile from "utils".
For HTML:
tools:::Rd2HTML(utils:::.getHelpFile(help(mtcars)))
For txt:
tools:::Rd2txt(utils:::.getHelpFile(help(mtcars)))
By the sounds of it, though, you should be able to use the function I've linked to in the comment above. For instance, to include the text from the "Description" section of the "mtcars" help page, you would use something along the lines of:
```{r, echo=FALSE, results='asis'}
cat(helpExtract(mtcars, section = "Desc", type = "m_text"))
```
I think you can get what you want by hacking the pager option as follows:
pfun <- function(files, header, title, delete.file) {
all.str <- do.call("c",lapply(files,readLines))
cat(all.str,sep="\n")
}
orig_pager <- options(pager=pfun)
help("mtcars")
options(orig_pager)
(you can return the character vector from the function instead of cat()ing it if you prefer).
Use printr, e.g.
library(printr)
help(mtcars)
detach('package:printr', unload = TRUE)