Related
I'm trying to render a table in R Markdown with several cells containing Greek letters. I use the following code to generate the table:
table <- readxl::read_excel("path/to/table.xlsx",
sheet = "data")
table %>%
knitr::kable(booktabs = TRUE)
While the output in the console is exactly what I want, I get the following error message when I try to knit the file to a PDF:
! LaTeX Error: Unicode character κ (U+03BA)
not set up for use with LaTeX.
I need to present the table with all the Greek letters. I've found information about getting Greek letters in the headings, but nothing about getting them to work in the body of the table. What is the best way to accomplish this?
Below is an example of the data I'm trying to render.
Any help would be very much appreciated!
Problems with encodings are eternal.
I can advice to you this solution.
Not so elegant, but it works.
Steps in console:
Activate the greek locale:
Sys.setlocale("LC_CTYPE", "greek")
Read the excel file:
table <- readxl::read_excel("table.xlsx", sheet = "N1")
Generate code for LaTeX:
table %>% knitr::kable(booktabs = TRUE, "latex")
Now we can transfer to rmd-file:
A simple example:
---
title: "Table"
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{polyglossia}
- \setotherlanguage{greek}
- \newfontfamily\greekfont[Script=Greek,Ligatures=TeX]{Times New Roman}
- \usepackage{booktabs}
---
Beautiful table:
\begin{greek}
\begin{tabular}{ll}
\toprule
Object1 & Object2\\
\midrule
ββ & λ\\
α & φ\\
\bottomrule
\end{tabular}
\end{greek}
Output:
I'm struggling to use stargazer output in knitr, using RStudio. For example, I paste the code below into a .Rmd file, then click Knit HTML. The first block between [ and ] is rendered as equations. The second block is from stargazer. It remains as code. When I paste the second block, less [ and ], into a Sweave file and then click compile as PDF, the code renders as a table. I have MikTex installed and version 3 of Stargazer.
The answer inserting stargazer or xable table into knitr document works for me in a Sweave file (Rnw) when clicking compile PDF. In an Rmd file, the tex is not rendered when clicking Knit HTML.
How can I put stargazer output into a Rmd file so that Knit HTML converts the latex code to a table? (I'm new to Latex, and am not sure what code I can delete, so apologise for the long segment.)
\[
\begin{aligned}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{aligned}
\]
\[
\documentclass{article}
\begin{document}
% Table created by StarGazer v.3.0.1 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
% Date and time: Sun, Feb 03, 2013 - 11:34:52 AM
\begin{table}[htb] \centering
\caption{}
\label{}
\footnotesize
\begin{tabular}{#{\extracolsep{5pt}}lc}
\\[-1.8ex]\hline
\hline \\[-1.8ex]
& \multicolumn{1}{c}{\textit{Dependent variable:}} \\
\cline{2-2}
\\[-1.8ex] & Rate \\
\hline \\[-1.8ex]
pole & $0.071^{***}$ \\
& $(0.020)$ \\
& \\
post & $0.095^{***}$ \\
& $(0.019)$ \\
& \\
Constant & $-5.784^{***}$ \\
& $(1.667)$ \\
& \\
\hline \\[-1.8ex]
Observations & $46$ \\
Residual Std. Error & $2.378 (df = 43)$ \\
\hline
\hline \\[-1.8ex]
\textit{Note:} & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
\normalsize
\end{tabular}
\end{table}
\end{document}
\]
Use the following code and you get a working version
```{r, results='asis'}
stargazer(model)
```
When converting to pdf, the following code works perfectly for stargazer 4.0:
```{r, results='asis'}
stargazer(model, header=FALSE, type='latex')
```
Since the topic has gone a bit stale, I'll assume the issue at hand is to somehow use stargazer with knitr, and not per se the conversion of the stargazer objects into HTML.
Being an avid fan of stargazer, I have come up with the following workflow:
Write my code in an .Rmd file.
Knit it into .md. Stargazer tables remain as LaTeX code in the resulting markdown file.
Use pandoc to convert the markdown file to PDF. Pandoc translates the LaTeX code into proper tables. Alternatively, one can use LyX with knitr plugin to get stargazer tables nicely output in PDF format.
If one wants stargazer tables in MS Word, the best way I have found is to use LaTeX2RTF. Although the very top cells are distorted a bit, fixing it is a matter of removing an erroneous empty cell. For the rest the table is preserved and can be pasted/imported into Word.
These two strategies help use stargazer outside LaTeX. Hope it helps.
In addition to the previous answer, and maybe as a simpler solution, it is possible for stargazer to output the table in html code so that when the Rmd file is knitted into html, a table is created rather than the tex code. I believe that the stargazer function can now export directly to html by setting type = 'html'.
So for example, given model fit lm1, you would use the following code in your Rmd file:
stargazer(lm1, type = 'html')
This works whether you want your final output to be html or pdf.
Returning to this question.
I want to use the same markdown files to produce html and pdf outputs in RStudio with knitr. That is, in RStudio I want to push the knit button, and have the options of either knitting a HTMl output, or a pdf output. I have no great interest, at the moment, in knitting a word/OpenOffice document.
I used the amazingly useful stargazer cheatsheet from Jake Russ. This exercises most of stargazer's functions. It is an R MArkdown file, with the chunk option
results='asis'
set for those chunks producing stargazer output.
The stargazer command itself has an argument 'type'. The default is
type='latex'
In Jake Russ's cheatsheet, which is intended to produce a webpage,
type='html'
is used throughout.
This does not work at all if you try to knit it into a pdf. Tables come out as long lists, one table cell per line, with no formatting, and occupying many pages, with no formatting.
The smallest change that I can make to allow me to produce nice pdf's within RStudio is to globally replace all the
type='html'
with
type='latex'
(note that both occur in the text of the document, as well as in the stargazer commands, so care is needed!)
This works! As far as I can see the pdf is a faithful replica of the webpage, which is exactly what I want.
Trying to knit OpenOffice documents, if I leave
type='latex'
Each table in the output is replaced by this text:-
% Table created by stargazer v.5.2 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu % Date and time: Tue, Sep 01, 2015 - 22:22:29
If I restore the
type='html'
then each table is written, one cell per line, down the side of the page with no formatting!
Stargazer is amazing but hasn't been updated in a while and so isn't designed to interact specifically with knitr or RStudio's interactive viewer options. The lack of interactive viewing and automatic html/latex detection leads to at least two issues:
This can be especially confusing for new users of R who expect easy-to-read inline output in RStudio
It can also be frustrating in more complicated documents when knitting a large html or latex table takes time
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
For more on RStudio's viewer function, rstudioapi::viewer(), see: https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html
The following four code chunks should work within a standard R markdown document and automatically assign the correct type (latex or html) when knitting. They should also run interactively and output inline and/or to the Viewer pane.
Finally, for automatic conversion of a stargazer table to formats that include Word (using an image of the html output) see this solution: https://stackoverflow.com/a/63563742/893399
```{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 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 am using knitr to parse an R Markdown document . Is there a way to conditionally display a block of text in R Markdown depending on a variable in the environment I pass into knitr?
For instance, something like:
`r if(show.text) {`
la la la
`r }`
Would print "la la la" in the resulting doc if show.text is true.
You need a complete R expression, so you cannot break it into multiple blocks like you show, but if the results of a block are a text string then it will be included as is (without quotes), so you should be able to do something like:
`r if(show.text){"la la la"}`
and it will include the text if and only if show.text is TRUE.
You can do this using the "eval" chunk option. See http://yihui.name/knitr/options/.
```{r setup, echo=FALSE}
show_text <- FALSE
````
```{r conditional_block, eval=show_text}
print("this will only print when show.text is TRUE")
```
I've been using YAML config files to parameterize my markdown reports which makes them more reusable.
```{r load_config}
library(yaml)
config <- yaml.load_file("config.yaml")
```
...
```{r conditional_print, eval=config$show_text}
print("la la la")
````
I find it easiest to do this by putting all of my text into a separate file and then include it from the main file with:
```{r conditional_print, child='text.Rmd', eval = show_text}
```
This has the advantage that you can still put inline R statements or other chunks into the child file, so that if you change your mind about what counts as optional text, you don't have to refactor your project.
Here's a tweak to Paul Boardman's approach that gives proper markup in the output.
```{r setup, echo=FALSE}
show_text <- FALSE
```
```{r conditional_block, echo=FALSE, results='asis', eval=show_text}
cat("## Hey look, a heading!
lorem ipsum dolor emet...")
```
Even better, if we invoke the python engine to generate our output, we can use triple quoting to easily handle text that contains single or double quotes without needing to do anything fancy:
```{python, conditional_block_py, echo=FALSE, results='asis', eval=show_cond_text}
print("""
## Still a heading
Block of text with 'single quotes' and "double quotes"
""")
```
The solutions above may be a little clunky for larger blocks of text and not great for certain situations. Let's say I want to create a worksheet for students with some questions and also use the same .Rmd file to generate a file with solutions. I used basic LaTeX flow control:
``` {r, include = F}
# this can be e.g., in a parent .Rmd and the below can be in child
solution <- TRUE
```
\newif\ifsol
\sol`r ifelse(solution, 'true', 'false')`
Then I can do:
What is $2 + 2$
\ifsol
4
\fi
This way you can also create alternative blocks of text using
\ifsol
Alternative 1
\else
Alternative 2
\fi
The accepted answer above works well for inline content.
For block content (one of several paragraphs of Markdown text), knitr contains a asis engine that allow to include Markdown content conditionnally depending if chunk option echo = FALSE or echo = TRUE
Example from the doc https://bookdown.org/yihui/rmarkdown-cookbook/eng-asis.html
```{r}
getRandomNumber <- function() {
sample(1:6, 1)
}
```
```{asis, echo = getRandomNumber() == 4}
According to https://xkcd.com/221/, we just generated
a **true** random number!
```
If you need to include more complexe content , like piece of a R Markdown document with e.g code block, then child document could be useful. See https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html
Another way to add markdown text conditionally is below. It uses the block "engine" which seems to run fine although I'm not sure how to make inline R evaluation working.
Note that I use the view_all switch defined in the YAML metadata to control whether or not the block is visible.
Also, note that both eval and include chunk options are needed.
The first prevents errors during regular Run All in RStudio.
The second prevents output with Knit.
---
title: "Conditional Output"
params:
view_all: false
output:
html_document: default
pdf_document: default
---
```{block eval=FALSE, include=params$view_all}
# Some simple markdown.
Some things work: $2 + 2^2 = 3\cdot2$
Other does not: 2 + 2 = `r 2+2`
```
I tried to define a function my.render(), which preprocesses the Rmd file, and depending on the commentout argument, either keeps the HTML commenting code (TRUE) in the Rmd file or removes them (FALSE). Then writes the preprocessed Rmd file into tmp.Rmd, and uses the usual render() function.
my.render <- function(input, commentout=FALSE, ...) {
if (commentout == FALSE) {
## Delete the HTML comment lines from code
txt <- readLines(input)
txt[grepl(" *<!-- *| *--> *", txt)] <- ""
write.table(txt, file="tmp.Rmd", sep="\n", quote=FALSE, row.names=FALSE, col.names=FALSE)
render("tmp.Rmd", output_file=sub("Rmd","html",input), ...)
} else {
render(input, output_file=sub("Rmd","html",input), ...)
}
}
It seemed to work. E.g.
<!--
This text with formulas $\alpha+\beta$ is visible, when commentout=FALSE.
-->
I'm struggling to use stargazer output in knitr, using RStudio. For example, I paste the code below into a .Rmd file, then click Knit HTML. The first block between [ and ] is rendered as equations. The second block is from stargazer. It remains as code. When I paste the second block, less [ and ], into a Sweave file and then click compile as PDF, the code renders as a table. I have MikTex installed and version 3 of Stargazer.
The answer inserting stargazer or xable table into knitr document works for me in a Sweave file (Rnw) when clicking compile PDF. In an Rmd file, the tex is not rendered when clicking Knit HTML.
How can I put stargazer output into a Rmd file so that Knit HTML converts the latex code to a table? (I'm new to Latex, and am not sure what code I can delete, so apologise for the long segment.)
\[
\begin{aligned}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{aligned}
\]
\[
\documentclass{article}
\begin{document}
% Table created by StarGazer v.3.0.1 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
% Date and time: Sun, Feb 03, 2013 - 11:34:52 AM
\begin{table}[htb] \centering
\caption{}
\label{}
\footnotesize
\begin{tabular}{#{\extracolsep{5pt}}lc}
\\[-1.8ex]\hline
\hline \\[-1.8ex]
& \multicolumn{1}{c}{\textit{Dependent variable:}} \\
\cline{2-2}
\\[-1.8ex] & Rate \\
\hline \\[-1.8ex]
pole & $0.071^{***}$ \\
& $(0.020)$ \\
& \\
post & $0.095^{***}$ \\
& $(0.019)$ \\
& \\
Constant & $-5.784^{***}$ \\
& $(1.667)$ \\
& \\
\hline \\[-1.8ex]
Observations & $46$ \\
Residual Std. Error & $2.378 (df = 43)$ \\
\hline
\hline \\[-1.8ex]
\textit{Note:} & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
\normalsize
\end{tabular}
\end{table}
\end{document}
\]
Use the following code and you get a working version
```{r, results='asis'}
stargazer(model)
```
When converting to pdf, the following code works perfectly for stargazer 4.0:
```{r, results='asis'}
stargazer(model, header=FALSE, type='latex')
```
Since the topic has gone a bit stale, I'll assume the issue at hand is to somehow use stargazer with knitr, and not per se the conversion of the stargazer objects into HTML.
Being an avid fan of stargazer, I have come up with the following workflow:
Write my code in an .Rmd file.
Knit it into .md. Stargazer tables remain as LaTeX code in the resulting markdown file.
Use pandoc to convert the markdown file to PDF. Pandoc translates the LaTeX code into proper tables. Alternatively, one can use LyX with knitr plugin to get stargazer tables nicely output in PDF format.
If one wants stargazer tables in MS Word, the best way I have found is to use LaTeX2RTF. Although the very top cells are distorted a bit, fixing it is a matter of removing an erroneous empty cell. For the rest the table is preserved and can be pasted/imported into Word.
These two strategies help use stargazer outside LaTeX. Hope it helps.
In addition to the previous answer, and maybe as a simpler solution, it is possible for stargazer to output the table in html code so that when the Rmd file is knitted into html, a table is created rather than the tex code. I believe that the stargazer function can now export directly to html by setting type = 'html'.
So for example, given model fit lm1, you would use the following code in your Rmd file:
stargazer(lm1, type = 'html')
This works whether you want your final output to be html or pdf.
Returning to this question.
I want to use the same markdown files to produce html and pdf outputs in RStudio with knitr. That is, in RStudio I want to push the knit button, and have the options of either knitting a HTMl output, or a pdf output. I have no great interest, at the moment, in knitting a word/OpenOffice document.
I used the amazingly useful stargazer cheatsheet from Jake Russ. This exercises most of stargazer's functions. It is an R MArkdown file, with the chunk option
results='asis'
set for those chunks producing stargazer output.
The stargazer command itself has an argument 'type'. The default is
type='latex'
In Jake Russ's cheatsheet, which is intended to produce a webpage,
type='html'
is used throughout.
This does not work at all if you try to knit it into a pdf. Tables come out as long lists, one table cell per line, with no formatting, and occupying many pages, with no formatting.
The smallest change that I can make to allow me to produce nice pdf's within RStudio is to globally replace all the
type='html'
with
type='latex'
(note that both occur in the text of the document, as well as in the stargazer commands, so care is needed!)
This works! As far as I can see the pdf is a faithful replica of the webpage, which is exactly what I want.
Trying to knit OpenOffice documents, if I leave
type='latex'
Each table in the output is replaced by this text:-
% Table created by stargazer v.5.2 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu % Date and time: Tue, Sep 01, 2015 - 22:22:29
If I restore the
type='html'
then each table is written, one cell per line, down the side of the page with no formatting!
Stargazer is amazing but hasn't been updated in a while and so isn't designed to interact specifically with knitr or RStudio's interactive viewer options. The lack of interactive viewing and automatic html/latex detection leads to at least two issues:
This can be especially confusing for new users of R who expect easy-to-read inline output in RStudio
It can also be frustrating in more complicated documents when knitting a large html or latex table takes time
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
For more on RStudio's viewer function, rstudioapi::viewer(), see: https://rstudio.github.io/rstudio-extensions/pkgdown/rstudioapi/reference/viewer.html
The following four code chunks should work within a standard R markdown document and automatically assign the correct type (latex or html) when knitting. They should also run interactively and output inline and/or to the Viewer pane.
Finally, for automatic conversion of a stargazer table to formats that include Word (using an image of the html output) see this solution: https://stackoverflow.com/a/63563742/893399
```{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)
```