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"
Related
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 Δ.
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.
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.
I'm using xtable to convert an R table into an object, which can then be printed as a LaTeX table. In this table, I need single numbers to be printed in different colors. Therefore, I already substituted these numbers before applying the xtable function using
paste0("\\textcolor{black!25!green}{",x.tab[[4]][i],"}",sep="")
where x.tab is my R table.
The .tex file looks fine and is compiling without any error. Still, I need these colored numbers, that are captured in a string now, with a decimal comma. All non-colored numbers are in the right format, because I use
format.args = list(big.mark = ".", decimal.mark = ",")
in my print function.
Any help is much appreciated!
In my case, using options(OutDec = ",") does the trick.
Use prettyNum function to set your format :
x <- c(1.6, 2.8, 1.3)
y <- c(0.067, 8.1, 7.55)
d <- data.frame(x, y)
print(xtable(prettyNum(d,decimal.mark=",")))
I am trying to format the table using gridExtra package. The gridExtra package I have is 2.0 and R version is 3.2.1
I was going through answers here on stackoverflow about the formatting and the suggested options seem to work only with older version of the package. For example,
grid.table(data, h.even.alpha = 1, h.odd.alpha = 0,
v.even.alpha = 1, v.odd.alpha = 1,
gpar.corefill, gpar.coretext)
All of these options are shown as "unused arguments" in the latest version.
Searching further, I found that in new gridExtra package, formatting is defined probably inside theme, example -
tt <- ttheme_default(core=list(fg_params=list(hjust=1, x=0.95)),
colhead=list(fg_params=list(col="brown"))
and then doing
grid.table(data, theme=tt).
What I could not found was how these options inside theme is defined and how all the formatting which was possible in older version can now be done.
In particular, I am looking to do -
Left justification of columns
commas for big.marks (10000 as 10,000)
different row colors for even and odd row numbers
column header color
not showing row names (something like row.names=FALSE)
This recent answer shows how to alter the parameters, and Baptiste gives a link to further examples. As you notice in your question, to alter the formatting you use the theme argument; you can see what parameters to alter by looking at the output of ttheme_default()
# New theme paramters
myt <- ttheme_default(
# Use hjust and x to left justify the text
# Alternate the row fill colours
core = list(fg_params=list(hjust = 1, x=1),
bg_params=list(fill=c("yellow", "pink"))),
# Change column header to white text and red background
colhead = list(fg_params=list(col="white"),
bg_params=list(fill="red"))
)
# Example data - create some large numbers
dat <- mtcars[1:5,1:5]
dat$mpg <- dat$mpg*1000
grid.newpage()
grid.draw(tableGrob(format(dat, big.mark=","), theme=myt, rows=NULL))
The big.mark argument of format is used to add the comma separator, and rownames are removed using the rows=NULL argument.
I'm trying to write a dashboard with shinydashboard in R to display some values using renderValueBox and valueBoxOutput. These values are not hardcoded but are being scraped from another source daily.
These values are currency numbers and should be reporting like $XXX,XXX.XX but instead I see XXXXXX.XX. Is there a way, like a wrapper, to easily format those values? Otherwise I've thought of brute forcing some regex on it with gsub...but ew. Please and thanks :)
Discovered the function prettyNum(): this function is amazing for simple conversion to comma separated numerics.
> prettyNum(56789, big.mark = ",")
> 56,789
Another way is to use the {scales} package and the dollar_format() function.
This function is a labelling function factory, in the sense that it creates other functions.
I usually need to output numbers in euros, so I defined the following function:
euro_format <- scales::dollar_format(
prefix = "\u20ac", # the euro symbol
suffix = "",
big.mark = ",",
decimal.mark = ".",
accuracy = 1
)
>euro_format(20842)
[1] "€20,842"