Use expression with a variable r
Asked Answered
L

5

45

I am trying to label a plot with the following label:

"Some Assay EC50 (uM)" where the "u" is a micro symbol.

I currently have:

assay <- "Some Assay"
plot(0,xlab=expression(paste(assay," AC50 (",mu,"M)",sep="")))

But that gives: "assay EC50 (uM)" rather than the desired "Some Assay EC50 (uM)".

Suggestions? Thanks.

I also tried:

paste(assay,expression(paste(" AC50 (",mu,"M)",sep="")),sep="")
Luminosity answered 25/2, 2013 at 18:46 Comment(0)
B
67

You want a combination of bquote() and a bit of plotmath fu:

assay <- "Some Assay"
xlab <- bquote(.(assay) ~ AC50 ~ (mu*M))
plot(0, xlab = xlab)

The ~ is a spacing operator and * means juxtapose the contents to the left and right of the operator. In bquote(), anything wrapped in .( ) will be looked up and replaced with the value of the named object; so .(assay) will be replaced in the expression with Some Assay.

Blackandwhite answered 25/2, 2013 at 18:55 Comment(0)
K
9

Using tidy_eval approach you could do

library(rlang)

assay <- "Some Assay"
plot(0,xlab=expr(paste(!!assay," AC50 (",mu,"M)",sep="")))

expr and !! are included in tidyverse, so you don't actually need to load rlang. I just put it there to be explicit about where they come from.

Kanara answered 4/12, 2018 at 10:31 Comment(0)
A
2

another option using mtext and bquote

plot(0,xlab='')
Lines <- list(bquote(paste(assay," AC50 (",mu,"M)",sep="")))
mtext(do.call(expression, Lines),side=1,line=3)

Note that I set the xlab to null in the first plot.

EDIT No need to call expression, since bquote will create an expression with replacement of elements wrapped in .( ) by their value. So a goodanswer is :

plot(0,xlab='')
Lines <- bquote(paste(.(assay)," AC50 (",mu,"M)",sep=""))
mtext(Lines,side=1,line=3)
Arched answered 25/2, 2013 at 18:59 Comment(3)
That defeats the point of bquote() which is to form an expression with replacement of elements wrapped in .( ) by their value.Blackandwhite
@GavinSimpson Thanks I get your point. Does it look better now?Arched
Not sure why, but I had to use do.call(expression, Lines) to make expression expanded, using the after-edit suggestion wrote literally the expression.Juvenilia
P
1

You also could try the poor man's approach:

assay <- "Some Assay"
plot(0, xlab = paste0(assay, " AC50 (µM)"))

It specifies the mu character directly rather than using expressions (and paste0 is just paste with sep = "").

Peruzzi answered 25/2, 2013 at 18:58 Comment(0)
S
0

Replacing expression() with eval() + parse() works when including a string variable.

Note that all spaces have to be replaced by ~, hence the call to gsub on the assay variable below. I've replaced the spaces in place in the rest of the label (e.g. " AC50 (mu*M)" --> "~AC50~(mu*M)")

assay <- "Some Assay"
plot(0,xlab=eval(parse(text = paste0(gsub(' ', '~', assay),"~AC50~(mu*M)"))))
Sclerosed answered 5/6 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.