How do you insert greek symbols into stargazer labels within markdown? - r

I am trying to insert a greek delta into a covariate label within stargazer. I have tried \Delta but it returns an error about the escape character '\D'. I have attempted with '\', wrapping in '$' and on and on.
What does work is to use the string 'CHG' and then replace all instances of 'CHG' in the html output with &#916.
Sample of R Markdown. Current reference to Delta returning 'delta' not the greek symbol.
I have tried one slash, 2, 3, 4. I have tried wrapping in '${ ... }$
output: html_doc
#```{r setup, include = FALSE, warning = FALSE, comment = FALSE}
library(dplyr)
library(stringr)
library(tidyr)
library(stargazer)
library(knitr)
x <- rnorm(1000)
y <- rnorm(1000)*x
df <- data.frame(x,y)
model1 <- lm(y~x, data = df)
#```{r Perf1.1, echo = FALSE, warning = FALSE, comment = FALSE, message = FALSE, results='asis'}
stargazer(model1, header=FALSE, type = 'html',
dep.var.labels = "\\Delta y")

Backslash is the escape character in R strings. To include it literally you therefore need to … escape it. So, double it up:
dep.var.labels = "\\Delta COGS_{t}",
However, this probably won’t work for HTML output, only for LaTeX output. For HTML, use the corresponding entity, or just use the Unicode character.

For some reason, it seems to work when you surround it with (any?) HTML tag. For example, what worked for me applied to your case would be:
dep.var.labels = "<strong>Δ</strong> COGS_{t}",

dep.var.labels = "<strong>Δ</strong> COGS_{t}
The answer above from #HLRA works for HTML code, not latex code. That is, the output of the "out.html" file can show the symbol of \Delta correctly.
But the latex code generated doesn't work as <strong> is not from the latex language.

I have no idea why but, putting 4 backslashes before any math input worked for me.

Related

printable table with partial bolding/italics within a cell

I'm looking for a way to print out a table from R, but with formatting within a cell, like having some of the text within a cell be bold or italic. Normally I would first make the appropriate data.frame/tibble and then I'd format and print it using a package like huxtable or kable. Looking over documentation for huxtable or kableExtra, it seems as though both packages treat formatting as properties of cells, implying that within-cell formatting is either unsupported or must be implemented some other way.
If I was making a ggplot, I'd use expression for text formatting, e.g.
library(tidyverse)
ggplot(data=mtcars) +
ggtitle(expression(paste(bold("bold part"), " not bold part")))
I thought I could be clever by putting expressions into a data.frame, but this doesn't seem to be supported:
data.frame(var = c(expression(paste(bold("bold part"), "not bold part")),
expression(paste(bold("bold part"), "not bold part"))
))
#> Error in as.data.frame.default(x[[i]], optional = TRUE): cannot coerce class ""expression"" to a data.frame
If you want to make changes to data tables, I recommend you use the grid and gridExtra packages to construct your table and then make changes to the theme parameters.
Without any data to play with I can't see exactly what you want but here's a general idea of what you could do (see below). I've included other aesthetic parameters, for future reference.
You could then generate a pdf output to your C drive, which could then be printed.
d <- data.frame(A = c(1,2,3,4,5),
B = c(6,7,8,9,10),
C = c(11,12,13,14,15))
pdf("Test.pdf", height = 11, width = 10)
grid.table(d, rows = NULL, theme = ttheme_minimal(
core=list(fg_params=list(
hjust=0,
x=0.1,
fontface=matrix(c(1,2,3))))))
dev.off()
Re huxtable, you're correct, but you can get round it. Here's a 1 row, 1 column example, assuming you are printing to HTML:
my_hux <- huxtable("<b>Bold part</b> Not bold part")
escape_contents(my_hux)[1, 1] <- FALSE
You can include arbitrary HTML. Something similar would work for TeX, obviously with TeX formatting instead.

Linked text in LaTeX table with knitr/kable

I have the following dataframe:
site_name | site_url
--------------------| ------------------------------------
3D Printing | https://3dprinting.stackexchange.com
Academia | https://academia.stackexchange.com
Amateur Radio | https://ham.stackexchange.com
I want to generate a third column with the link integrated with the text. In HTML I came up with the following pseudo code:
df$url_name <- "[content of site_name](content of site_url)"
resulting in the following working program code:
if (knitr::is_html_output()) {
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df)
}
Is there a way to this in LaTeX with knitr as well?
(I am preferring a solution compatible with kableExtra, but if this is not possible I am ready to learn whatever table package can do this.)
*** ADDED: I just noticed that the above code works within a normal .Rmd document with the yaml header output: pdf_document. But not in my bookdown project.
The problem is with knitr::kable. It doesn't recognize that the bookdown project needs Markdown output, so you need to tell it that explicitly:
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df, format = "markdown")
This will work for any kind of Markdown output: html_document, pdf_document, bookdown::pdf_book, etc.
Alternatively, if you need LaTeX output for some other part of the table, you could write the LaTeX equivalent. This won't work for HTML output, of course, but should be okay for the PDF targets:
df <- df %>% dplyr::mutate(urlName = paste0("\\href{", df[[2]], "}{", df[[1]], "}"))
knitr::kable(df, format = "latex", escape = FALSE)
For this one I had to change the column name; underscores are special in LaTeX. You could probably get away without doing that if you left it as format = "markdown", but then you'd probably be better off using the first solution.

Changing the decimal mark makes stargazer to put an extra space between numbers

I'm using the library stargazer to generate tables in latex (Rstudio/knitr/Sweave).
I need to change the decimal separator to comma (",") and the function stargazer() works most of the times. Only when the option summary = false is passed the results come with a extra space between numbers.
Anyone knows how to overcome this problem?
<<results='asis'>>=
library(stargazer)
set.seed(0)
x = matrix(rnorm(3),nrow = 1)
y = matrix(rnorm(9),nrow = 3)
stargazer(x,summary=FALSE)
stargazer(x,summary=FALSE,decimal.mark = ",")
stargazer(y,summary=TRUE,decimal.mark = ",")
#
Table 2 always shows a extra space between the comma and the first decimal place. Table 3 shows good results
When inspecting the generated TEX it becomes clear that stargazer does not add any spaces after the commas. The problem lies somewhere else:
The root of this problem is that LaTeX does not recognize , as a decimal separator by default. Therefore, when in math mode, LaTeX adds a space after each ,. This problem is described here on TEX.SE and the solution is to include the icomma package.
\documentclass{article}
\usepackage{icomma}
\begin{document}
<<results='asis', echo=FALSE, message = FALSE>>=
library(stargazer)
set.seed(0)
x = matrix(rnorm(3),nrow = 1)
y = matrix(rnorm(9),nrow = 3)
stargazer(x,summary=FALSE)
stargazer(x,summary=FALSE,decimal.mark = ",")
stargazer(y,summary=TRUE,decimal.mark = ",")
#
\end{document}
One question remains: Why was the problem not visible in Table 3 from the question? This is because stargazer uses inconsistent math markup in the tables. The second cell in Table 2 contains $$-$0,326$ whereas row 2, last column of Table 3 contains $-$0,006. In the first case, the number itself is in math mode, leading to the behavior described above. (And unfortunately, the - is in text mode, leading to bad typography.) In the second case, the number is in text mode, where no extra space is added.
To overcome the issue with the badly formatted minus signs, I recommend using xtable instead of stargazer for the simple (non-summary) tables. Combined with a custom column type that sets the column in math mode, the result is:
\documentclass{article}
\usepackage{icomma}
\usepackage{tabularx}
\newcolumntype{R}{>{$}r<{$}} % like an "r" column but in math mode
\begin{document}
<<results='asis', echo=FALSE>>=
library(xtable)
set.seed(0)
x = matrix(rnorm(3),nrow = 1)
print.xtable(
xtable(x, caption = "", align = rep("R", 4)),
include.rownames = FALSE,
include.colnames = FALSE,
format.args = list(decimal.mark = ","),
caption.placement = "top")
#
\end{document}

R plotmath - how to display an apostrophe

I am trying to print an apostrophe for the column name below in a table using tableGrob
"Kendall's~tau"
The end result is that the whole label is italicized without the ~ and tau being interpreted:
How do I correctly specify this?
I don't think it's helpful, but this is the theme that I've specified to tableGrob:
table_theme <- ttheme_default(
core = list(fg_params=list(fontsize = 6)),
colhead = list(fg_params=list(fontsize = 6, parse=TRUE)),
rowhead = list(fg_params=list(fontsize = 6, parse=TRUE)),
padding = unit(c(2, 3), "mm"))
The column name is interpreted via plotmath in grDevices -- the standard way of specifying mathematical annotation in figures generated in R.
Again it has nothing to do with how to specify the expression itself, but here is the table constructor:
tableGrob(stats_df,
theme = table_theme,
rows = c("Kendall's~tau"))
Here's a reproducible example:
library(gridExtra)
library(grid)
data(iris)
table_theme <- ttheme_default(rowhead = list(fg_params=list(parse=TRUE)))
grid.table(head(iris),
rows = c(letters[c(1:4)], "plotmath~works~omega", "Kendall's~tau"),
theme = table_theme)
This works:
library(gridExtra)
library(grid)
data(iris)
table_theme <- ttheme_default(rowhead = list(fg_params=list(parse=TRUE)))
grid.table(head(iris),
rows = c(letters[c(1:4)], "plotmath~works~omega", "Kendall's"~tau),
theme = table_theme)
Try with a backslash in your expression like "Kendall\'s~tau". It should work then.
I tried to use apostrophe with expressions to plot in ggplot. In my database is invalid to use ' in expressions, but this worked
expression(paste(u,"'",(t),sep=""))
But this "paste" also cause bad behaviour of the subindex expression expression(U[0]). So to use both together, this one worked
paste(expression(paste("u","'",sep="")),"/U[0]",sep="")
If anyone knows a easier way, I'd be very glad.
If your apostrophe is embedded in a longer string, along with special symbols like ~, these solutions will not work. The only thing I've found to work is using regular expression substitution.
#This doesn't work
stringWithApostrophe="Matt's and Louise's diner~...and~also Ben's diner~X^2"
qplot(1:10,1:10)+annotate("text",x=2,y=4,label=stringWithApostrophe,parse=T)
Error: "Error in parse(text = text[[i]]) : :1:5: unexpected string constant"
The problem is the special characters like tilde and apostrophe happening in the same quoted segment. So you have to separate "Matt's" from "Louise's" and "~". Here's the code to do that.
stringWithApostrophe2<-stringr::str_replace_all(pattern = "([^~()*]*'[^~()*']*)",replacement = "\"\\1\"",string=stringWithApostrophe)
qplot(1:10,1:10)+annotate("text",x=2,y=8,hjust=0,label=stringWithApostrophe2,parse=T)
Plots successfully. The final expression that plotmath in R parses correctly is:
""Matt's and Louise's diner"~...and~"also Ben's diner"~X^2"

multiline table header using knitr and latex [duplicate]

This question already has answers here:
Simple example of using tables + knitr for latex
(2 answers)
Closed 7 years ago.
I ended up using tables package with knitr, but I can not figure out how to get a multiline header. Here is the code:
<<test_table, results='asis', echo=FALSE>>=
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c("first column", "seconf column which I want to have 2 lines because of its very long header title", "third column")
library(tables)
table <- as.tabular(matrix)
latex(table)
#
It's probably possible to do this with the tables package, but xtable provides a very easy solution. The following minimal example shows two different approaches:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE>>=
library(xtable)
library(knitr)
opts_chunk$set(echo = FALSE, results = "asis")
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c(
"first column",
"second column which I want to have 2 lines because of its very long header title",
"third column")
#
<<ChangeColumnType>>=
print(xtable(matrix, align = c("r", "r", "p{4cm}", "r")), include.rownames = FALSE)
#
<<ChangeOnlyCell>>=
colnames(matrix)[2] <- "\\multicolumn{1}{p{4cm}}{second column which I want to have 2 lines because of its very long header title}"
print(xtable(matrix), include.rownames = FALSE, sanitize.colnames.function = identity)
#
\end{document}
The first approach (chunk ChangeColumnType) is very simple: It sets the column type of column 2 to p{4cm}. That gives a column that is 4cm wide with automatic text wrapping (see wikibooks.org for more details). The drawback is, that this affects the whole column, not only the cell in the first row.
The second approach (chunk ChangeOnlyCell) uses default alignment (or whatever you want to specify via align) and changes only the column type of the problematic cell using \multcolumn.
By default, xtable "sanitizes" your table, meaning that all special latex characters will be escaped. This is handy because you cannot (easily) break your TEX code, but here we manually want to inject LaTeX code, so we have to turn this off. Therefore, set sanitize.colnames.function = identiy. All column names will be used as you specify them – so be careful when using characters with a special meaning in LaTeX.
The example from above delivers the following tables:

Resources