First of all let me say that when I knit a full document that the output of stargazer is as expected. What I'd like to do is render it in my source pane under the block of code like I can with any other type of code, including plots. So far the best I've found is setting startype<-ifelse(is.null(opts_knit$get("rmarkdown.pandoc.to")), 'text', 'html') and then in my call to stargazer settings type=startype that way when I knit I get the fully formatted version but in my code chunk I still get something. I'd like to be able to get the fully formatted version so I can tweak the parameters according to how it'll finally look without having to knit the whole thing.
I'm on Windows with Rstudio version 1.4.1106
Is that possible?
Below I've created a simple wrapper around the stargazer function called starviewer that does the following:
check if the document is being knit to latex or html
if the document isn't being knit to latex, output to text or html
when run interactively in RStudio, output can appear inline as text and/or in the Viewer pane as html
I'm not expert with the rstudioapi::viewer() options but this worked well on my system.
For more on the rstudioapi, see: https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html
Copy the following four code chunks into an Rmd and they should be able to run interactively or be knit to latex or html automatically depending on the user action.
```{r load_packages}
# good to load stargazer for regular usage
library(stargazer)
```
```{r starviewer_function}
# create wrapper around stargazer
starviewer <- function(...) {
# make sure stargazer is available
require(stargazer)
# assume text output but check for latex or html
star_format <- "text"
if(knitr::is_latex_output()) {star_format <- "latex"}
if(knitr::is_html_output()) {star_format <- "html"}
# if latex, just run stargazer as usual
if (star_format == "latex") {
stargazer::stargazer(...)
} else {
# if not latex, run stargazer in text / html (or both)
dir <- tempfile()
dir.create(dir)
htmlFile <- file.path(dir, "tempfile.html")
stargazer::stargazer(..., type = star_format, out = htmlFile)
rstudioapi::viewer(htmlFile)
}
}
```
```{r run_models}
lm1 <- lm(mpg ~ wt, data = mtcars )
lm2 <- lm(mpg ~ wt + am, data = mtcars )
```
```{r create_table, results = 'asis'}
starviewer(lm1, lm2)
```
Related
Is it possible to export the R script to a PDF and/or Word document without the outputs (i.e. without whatever the console prints; plots, graphs etc.)? I know about the r markdown package but as far as I know, it exports the script only with outputs.
rmarkdown is very flexible, you don't have to include output. If you set the option eval = FALSE none of the code will be evaluated, so no outputs will be generated.
See here for a detailed list of options available at the code-chunk level.
To follow up on #GregorThomas's answer: if you simply add R code block-formatting around all of your code with eval=FALSE specified and save it with an .rmd extension, you can then click "Knit to PDF" in RStudio (which will automatically add a minimal header). I think you could probably also do rmarkdown::render("myfile.rmd", output_format = "pdf_document"). If you wanted you could set up a little script to do the minimal editing and rendering automatically ...
```{r eval = FALSE}
x <- 2+3
print("hello")
```
Something like (untested!)
printme <- function(file) {
tt <- tempfile(fileext = ".Rmd")
writeLines(c("```{r eval=FALSE}",
readLines(file),
"```"),
tt)
rmarkdown::render(tt, output_format = "pdf_document",
output_file = "out.pdf")
}
Is it possible to place a table generated with the xtable (or alternatively the pander) package and a generated plot side-by-side in R markdown knitting to pdf while the rest of the document is not in columns? The following simple example hopefully illustrates the idea:
\begin{multicols}{2}
```{r}
plot(cars)
```
```{r, results='asis'}
library('xtable')
print(xtable(head(cars,5)), type = "latex")
```
\end{multicols}
However, this does not produce the plot. I know that solutions exist using knitr (e.g. here) and for R markdown knitting to HTML (e.g. here) but I don't get them to work for R markdown to pdf.
the gridExtra package works for this without having to go into LaTeX hell. Use the grid.arrange function for side by side charts and what-not.
Works on html and PDF outputs.
Thank you #nycrefugee this already opens some more opportunities. However, there seem to be some problems with xtable outputs. If I use the following code:
library('gridExtra')
library('grid')
library('xtable')
library('lattice')
p = xyplot(1~1)
t = textGrob( print(xtable(head(cars,5)),
type = "latex", label = "test")
)
grid.arrange(p, t, ncol=2)
it produces the following output when compiled to pdf, i.e. the table is shown above the two grobs:
PDF output
I'm trying to produce an automated report using Rmarkdown. In this report I have sections with tables. The sections are produced using the following Rmarkdown. However, it refuses to produce any tables(tried using kable and pander) when I hit knit. Knit will just produce the headings, without any tables. When I use the immediate mode, I get the appropriate markdown. So what might I be doing wrong.
```{r, results='asis'}
for(p in names(presentations)) {
deats <- presentations[p][[1]]
cat('#', p, '\n')
pander(deats)
str(deats)
cat('\n')
}
```
If using pander, disable the auto asis results:
```{r, results='asis'}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
for(p in names(mtcars)) {
cat('#', p, '\n')
pander(table(mtcars[, p]))
}
```
For more details, see the related Using pander with knitr vignette
When knitr::kable() or pander::pander() is not top-level R expression, you have to explicitly print it. You may see this post for more background information.
I have a shiny app (radiant.data) that uses knitr to generate reports viewable inside the application (R > Report). Because the output is displayed inside a shiny app I need a render function for something like a DT table to be displayed (i.e., convert to shiny.render.function). This all works fine.
Now, however, I want to use a custom print method to handle rendering so I can just use DT::datatable(mtcars) with knitr and knit_print.datatables to generate a shiny.render.function.
Below some example R-markdown that includes the knit_print.datatables function i'm using. chunk1 and chunk2 show a shiny.render.function as intended but the chunk6 shows nothing. If screenshot.force = TRUE I get a screenshot from chunk6 but that is not what I want either.
Example R-markdown to be processed with knitr::knit2html
```{r chunk1}
knitr::opts_chunk$set(screenshot.force = FALSE)
DT::renderDataTable(DT::datatable(mtcars))
```
```{r chunk2}
knit_print.datatables <- function(object, ...) {
DT::renderDataTable(object)
}
```
```{r chunk3}
knit_print <- knitr::knit_print
knit_print.datatables(DT::datatable(mtcars))
```
```{r chunk4}
getS3method("knit_print", "datatables")
```
```{r chunk5}
class(DT::datatable(mtcars))
```
```{r chunk6}
DT::datatable(mtcars)
```
I realize the R-markdown above, although reproducible if you have knitr and DT installed, looks a bit weird but when I export the knit_print.datatables function properly I get the same result in my application (see example output below).
I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.