So I'm also preparing a table or regression results in stargazer, and I'm only showing the t-scores in the table from 10 different models side by side. I have the same question as in this earlier post on how to remove the "t = " from the stargazer results output from #deca.
I've followed the answer given by #JNWHH, which is:
Access the edit-screen of the stargazer function with trace(stargazer:::.stargazer.wrap, edit = T)
Go to line 7103/7104 (may be different depending on your stargazer version) and look for .format.t.stats.left <- "t = " and .format.t.stats.right <- "" and edit it to your liking, e.g., .format.t.stats.left <- "[" and .format.t.stats.right <- "]"
Confirm with "save".
After completing these three steps and then calling the stargazer function again, I can see in the LaTeX code produced for my table that all of the "t = " have been removed. However, when I knit the document, the resulting PDF still has the "t = " in them.
I wasn't sure what/if code was needed here for people to diagnose, but if so, please let me know and I can try to include what I'm running. But really, I'm just following the three steps above exactly as described. I have not restarted my R-session since editing the source code, so I don't think the problem stems from that. If I'm missing something obvious, thanks for letting me know.
I gone through the solution. You have to adjust the stargazer source code while knitting the document. This is true for either text in html or latex in PDF output.
---
title: "stargazer_edits"
author: "Me"
date: "2023-01-13"
output:
html_document: default
pdf_document: default
---
## stargazer source edited
```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(stargazer)
# I do this once
trace(stargazer:::.stargazer.wrap, edit = T)
model <- lm(mpg ~ disp + cyl, data=mtcars)
stargazer(model, type = "text", report = "vc*t")
```
While producing the document this opens the source code.
You can more easily find the part .format.t.stats.left (lines 7105 and 7106 at 13.01.2023) by searching the text file. You modify the style, e.g. change it to square brackets.
Related
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)
```
I created a custom function which sets mfrow to nxn and creates n^2 scatter plots, with multiple data sets on each plot, based on an input list of data frames. The signature of my plotting function looks like this:
plot.return.list<-function(df.list,num.plot,title)
Where df.list is my list of data frames, num.plot is the total number of plots to generate (used to set mfrow) and title is the overall plot title (the function generates titles for each individual sub-graph).
This creats plots fine when I run the function from the console. However, I'm trying to get this figure into a markdown document using RStudio, like so:
```{r, fig.height=6,fig.width=6}
plot.return.list(f.1.list,4,bquote(atop("Numerical Approximations vs Exact Soltuions for "
,dot(x)==-1*x*(t))))
```
Since I haven't set the echo option in my {r} statement, this prints both the plotting code as well as the plot itself. However, if my first line instead reads:
{r, fig.height=6,fig.width=6,echo=FALSE}
Then both the code AND the plot disappear from the final document.
How do I make the plot appear WITHOUT the code? According to the example RStudio gives, setting echo=FALSE should make the plot appear without the code, but that isn't the behavior I'm observing.
EDIT: I seem to have tracked my problem down to kable. Whether or not I'm making a custom plot-helper function, any call to kable kills my plot. This can be reproduced in a markdown:
---
title: "repro"
author: "Frank Moore-Clingenpeel"
date: "October 9, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
options(default=TRUE)
repro.df<-data.frame((0.1*1:10)%*%t(1:10))
```
```{r, echo=FALSE}
kable(repro.df)
```
```{r, fig.height=6,fig.width=6,echo=FALSE}
plot(repro.df[,1],repro.df[,2])
```
In this code, the plot won't plot because I have echo set to false; removing the flag makes the plot visible
Also note that in my repro code, kable produces a table with a bunch of garbage in the last line--I don't know why, but this isn't true for my full original code, and I don't think it's related to my problem.
Thanks for the reproducible example. From this I can see that the problem is you don't have a newline between your table chunk and your plot chunk.
If you were to knit this and examine the MD file produced by knit (or set html_document as your output format and have keep_md: true to look at it), you would see that the table code and plot code are not separated by any newline. Pandoc needs this to delimit the end of the table. Without it, it thinks your ![](path/to/image.png) is part of the table and hence puts it as a "junk line" in the table rather than an image on its own.
Just add a newline between the two chunks and you will be fine. (Tables need to be surrounded with blank lines).
(I know you are compiling to LaTeX so it may confuse you why I am talking about markdown. In case it does, when you do Rmd -> PDF, Rmarkdown uses knit to go from RMD to MD, and then pandoc to go from MD to tex. This is why you still need to make sure your markdown looks OK).
I am creating a Word report with R studio, markdown and knitr and I am having some troubles.
My r code includes several chunks, becauase between chunks, I want to include the text my report should include.
The problem I have is that: if use a single chunk, then the report is ok, but I can't include text/comments to be written in the report, unless I print also the code (right?). But if I use multiple chunks, then, when compiling, plots are not included in the report and warning messages appear:
pandoc.exe: Could not find image `Scriptv01_files/figure-docx/4.PLOTS-1.png', skipping...
It only works with HTML output: report includes all plots, but not with DOC nor PDF output.
I think the issue is that the data object is created in a different chunk, but I have tried 'cache' and 'autodep' options with no success.
How can this be done? What's the problem with the code?
Many thanks!
Here I provide a code example:
---
output: word_document
---
# PROJECT: IRIS STUDY
#### Statistical Analysis
```{r setup}
require(knitr)
opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE, comment='')
```
```{r read data}
dataset<-iris
```
### Data Descriptive by Iris Specie
```{r 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE}
require(ggplot2)
ggplot(dataset, aes(Species)) + geom_bar(aes(fill=Species))+
labs(x = "Species", y = "Number of Flowers")+ ggtitle("Fisher's Iris data set")
```
knitr uses the chunk name as part of the image file name. The chunk name 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE is invalid and is the reason why the plot is not being created. Replacing the name by a valid name solves the problem:
Avoid spaces and periods . in chunk labels and directory names [Source]
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.
I'm writing an Rmd file, to be processed by knitr into HTML. It contains some R chunks that generate figures, which get stored as data URIs in HTML.
1) How do I add a caption to such an image? I'd like to have a caption that says something like "Figure 3: blah blah blah", where the "3" is automatically generated.
2) How do I later on reference this image, i.e., "as you can see in Figure 3, blah blah".
I'm late to the party, but I wanted to mention a small package I recently built to do figure captioning and cross-referencing with knitr. It is called kfigr and you can install it using devtools::install_github('mkoohafkan/kfigr'). It is still in active development but the main functionality is there. Be sure to check out the vignette, it shows some usage examples and defines some hooks for figure captions and anchors (I may later choose to have the package import knitr and define those hooks on load).
EDIT: kfigr is now available on CRAN!
You can create the figure numbers with a simple counter in R; see one example here. The problem is whether the markdown renderer will render the figure caption for you: R Markdown v1 won't, but v2 (based on Pandoc) will.
I do not know. There is no direct way to insert a label as an identifier for figures, so it is probably not possible to cross reference figures with pure Markdown. Once you've got issues like this, think (1) do I really need it? (2) if it is intended to be a document with a complicated structure, I think it is better to use LaTeX directly (Rnw documents).
Also very late to the party I changed Yihuis suggestion here that he also linked above to do referencing.
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
```{r cars, echo=FALSE, fig.cap=fig$cap("cars", "Here you see some interesting stuff about cars and such.")}
plot(cars)
```
What you always wanted to know about cars is shown in figure `r fig$ref("cars")`
One way to do both of these is described here: http://rmflight.github.io/posts/2012/10/papersinRmd.html
Another is described here (but I don't know if it does your #2). http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/
Another solution:
https://github.com/adletaw/captioner
From the README:
captioner() returns a captioner function for each set of figures, tables, etc. that you want to create. See the help files for more details.
For example:
> fig_nums <- captioner()
> fig_nums("my_pretty_figure", "my pretty figure's caption")
"Figure 1: my pretty figure's caption"
> fig_nums("my_pretty_figure", cite = TRUE)
I did both (figure numbers + references) with bookdown. I added in output section in the header of the file:
output:
bookdown::html_document2:
fig_caption : TRUE
Then I created a figure in a R code chunk like follows:
{r, my-fig-label,echo=F, eval=T, fig.align = 'center', fig.cap="This is my caption"}
knitr::include_graphics(here::here("images", "my_image.png"))
This produces an automatic number under your figure. You can refer to it with \#ref(fig:my-fig-label).
Using the official bookdown documentation 4.10 Numbered figure captions:
---
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r mtcars, fig.cap = "Another amazing plot"}
plot(mpg ~ hp, mtcars)
```