Using expression and paste in R to format an ion name with units in parantheses - r

I want to create a clean label to a graph that has the species abbreviation of an ion (in this case Chloride) followed by the concentration units (micro equivalents per liter) enclosed in parentheses. As written, the code mostly produces this, but superscripts the parentheses/units section. Probably missing something small. Using this code snippet with the ylab() command in ggplot2 as a label. Thanks.
My code so far:
cl.label = expression(paste(Cl^- ~(mu~eq ~L^-1)), parse=TRUE)

In the expression, - is an operator so it needs something to "negate." You can give it a phantom object like
cl.label = expression(Cl^-phantom() ~(mu~eq ~L^-1))
or you can treat the - as a literal dash value with
cl.label = expression(Cl^"-" ~(mu~eq ~L^-1))

Related

Functions to format text for base R plotting

Specifying text in a base R plot() with formatting such as italics / bold font / newline usually involves one or more of the following functions:
paste()
expression()
atop()
substitute()
italic()
Is there an intuitive explanation for the differences between these functions and when best to apply them?
What you're referring to is the plotmath syntax.
To start off, let's make it clear that for a plotmath expression to be interpreted as such, you tell R it's an "expression" and that is why you need expression().
So any time you want to use special symbols or formatting, like italic() and atop(), it's actually a part of plotmath and so you need to wrap it in an expression. eg:
plot(0, main = expression(atop(over,italic(under))))
If you've tried out ?italic or ?atop, you've probably noticed it takes you straight to the plotmath manual page, where a bunch of other functions are listed.
What about substitute() ? Well in my previous example, you'll notice I used strings directly to write 'over' and 'under', without putting them within quotes. This is because of the special expression() environment.
So if you need to put whatever is inside a variable in your text (rather than the variable name) then you put your expression inside a substitute() and give it the arguments. eg:
plot(0, main = substitute(atop(oo,italic(under))), list(oo='over2')))
Note that we don't put substitute around the expression block but replace it entirely.
Finally, where does paste() come in all this ? Well, paste is the glue (pun intended) with any text not dealt with by plotmath.
So if you need text before or after math symbols (or formatted text), you paste() things together within the expression (or substitute) environment. eg :
plot(0, main = substitute(paste("b4", atop(oo,italic(under)), aft),
list(oo='over', aft = 'after3')))
As before, if you want to paste the content of a variable, you need substitute.
And Voilà that's most of the plotmath you'll ever need!
For any other symbols, or functions, have look at ?plotmath

Insert specific unicode symbols inside values of data.frame variable

In my data.frame I would like to add two variables, "A" and "B", whose values contain respectively an n with the i subscript and an n with the s subscript.
As I have understood so far, it's not possible to specify an expression for the values of a variable, and hence to add special characters it's necessary to use unicode symbols. Some of this unicodes work in R, as for example the greek letter "mu", identified with the unicode \U00B5, or numeric subscripts, as you can see in this reprex in your R console:
x <- data.frame("A" = c("\U00B5"),
"B" = c("B\U2082"))
print(x)
These unicodes work also if I decide to put this variable in a ggplot() object, because I will display the correct symbol ("mu" for example) on the axis text or the facets.
The problem is that when I do the same for the subscripts of i (unicode: \U1D62) and s (unicode: \u209B), R doesn't recognise the unicode and prints the whole string inside the variable name.
Do you know how I can resolve this issue and if this unicode works on every operating system?
Thanks
Is there a reason you can't use the expression() function? It seems this would solve your problem (at least concerning greek letters).
Here is the site i used to learn how to input greek letters into my R/ggplot-legends.
https://stats.idre.ucla.edu/r/codefragments/greek_letters/
Altough it is not exactly the answer you look for, i still hope it helps!
If you are on Windows 10 recently updated with as of April 2018 Update:
Use the Windows key + '.' (e.g. hold together Windows Key plus period) in your text editor. This brings up Microsoft Emoji keyboard.
Select the Greek letters variable for your script.
The R Console will not accept the Greek letters as variables directly but only the from the editor script. Some of the Greek letters don't translate to English (like "µ" or "ß".) You can paste and copy them from ls() output to access. You may be able to use some math symbols as well for variable names. I can't however, get this to work with source(). That must be a text encoding problem.

How to add a space to an object name in R

Piston_Rings<-diameter[1:25,]
I want my quality control graph NOT to have the underscore in the object name.
At the moment there is an underscore (not a hyphen) in that object name. It is possible to construct objects whose names have spaces in them but in order to access them you will then always need to use backticks in order to get the interpreter to understand what you want:
> `Piston Rings` <- list(1,2)
> `Piston Rings`[[1]]
[1] 1
> `Piston Rings`[[2]]
[1] 2
The problem you incur is cluttering up your code, at least relative to obeying the usual conventions in R where a space is a token-ending marker to the parser. Hyphens (at least short-hyphens) are actually minus signs.
If on the other hand you only want to use a modified version of a name that contains an underscore as the title for a graph, then try something like this:
Piston_Rings <- list() # just for testing purposes so there will be an object.
plot( 1:10,10:1, main = sub("_", " ", quote(Piston_Rings)) )
#BondedDust's answer is correct, but (guessing, since you haven't been very specific) a simpler way to get what you want is just to specify xlab or ylab arguments to the plot() function. Let's say you have variables stuff (x) and Piston_Rings (y). If you just
plot(stuff,Piston_Rings)
then the plot will have "Piston_Rings" as the y-axis label. But if you
plot(stuff,Piston_Rings,ylab="Piston Rings")
you'll get the label you want. You can also include lots more information this way:
plot(stuff,Piston_Rings,
xlab="Important stuff (really)",
ylab="Piston Rings (number per segment)")
See ?plot.default for many more options.

How to make the font bold in R's bquote for main of plot?

I make some plots with R and use bquote because I need variables for the main of the plot. However, the main is no longer bold but I want it to be bold. I defined the main as follows:
title = bquote(atop("Empirical Pricing Kernel at Date",~.(EndDate)~"with Index Price"~.(ST)~"€"))
plot(temp, EPK, type="l", main = title)
Enddate contains "2014-08-01" as date and ST is just numeric with 9210.08.
Is there any way to make it bold with or without bquote? I'd like to find a solution with bquote because it's very convenient when using subscripts.
My problem is that I am using it in a par-plot with two plots and the other plot needs no special things in it's main. So, the main is bold. I even tried to just put bquote around it in order to get the same font size but it stayed bold.
I prefer to use what I think of as "pure plotmath" so I use tilde's instead of spaces and use no quotes. I suspect it was the leading tilde in the second argument to bquote that was throwing the error. In plotmath the tildes need something on either side: If you really need a none-displayed something you can always use phantom(0) but why bother in this case?
bquote(atop(Empirical~Pricing~Kernel~at~Date,
bold(.(EndDate))~with~Index~Price~.(ST)~"€"
) )
Test:
EndDate="2014-08-01";ST=9210.08
title = bquote(atop(Empirical~Pricing~Kernel~at~Date, bold(.(EndDate))~with~Index~Price~.(ST)~"€"))
plot(1,1, type="l", main = title)

How to include multiple \Sexpr values within LaTeX math mode tags?

As part of my work, I am expected to show calculation steps with sample values. To do this, I usually just replace the variable names with \Sexpr{} to add in the values. For some reason \Sexpr{} escapes math mode and breaks some of my tags. For instance, this works well:
$r_{pump} = \sqrt{(x_{pump} - x_{obs})^{2} + (y_{pump} - y_{obs})^{2}}$
It results in all values being correctly placed under the square root tag like this:
However, when I try to include \Sexpr{} tags to incorporate values like this...
$\sqrt{(\Sexpr{x[1]}(m) - \Sexpr{x[2]}(m))^{2} + (\Sexpr{y[1]}(m) - \Sexpr{y[2]}(m))^{2}}$
...I get results that look like this:
This happens when I try to include \Sexpr{} in a \frac{}{} tag as well.
Am I applying math mode ($\Stuff$) incorrectly?

Resources