0

I am trying to evaluate a variable inside theexpression function. The function works fine when the variable has no value and is just a string.

> plot(rnorm(30), xlab = expression(value~2^-dCT))

enter image description here

But when value is a variable, the value of the variable gets ignored...

> rm(value)
> value = "some text"
> plot(rnorm(30), xlab = expression(value~2^-dCT))

enter image description here

I also tried > plot(rnorm(30), xlab = expression(eval(value)~2^-dCT)) and had a similar issue... enter image description here

plot(rnorm(30), xlab = expression(paste(value~2^-dCT))) does not work as well. Any help would be appreciated, thank you!

Noah_Seagull
  • 337
  • 5
  • 18
  • see e.g. `?bquote` – Ben Bolker Feb 03 '22 at 21:39
  • Thanks, that helped a lot. It brought me to this [post](https://stackoverflow.com/questions/15074127/use-expression-with-a-variable-r) where the same question was asked. My bad, I was not aware this function existed. – Noah_Seagull Feb 03 '22 at 21:53
  • No need for an apology; if you knew, you wouldn't need to ask (and searching for duplicates on SO is unfortunately not that easy) – Ben Bolker Feb 03 '22 at 22:06

1 Answers1

1

Here are several ways:

value <- "some text"

# 1
plot(0, xlab = substitute(value ~ 2^-dCT, list(value = value)))

# 2
plot(0, xlab = bquote(.(value) ~ 2^-dCT))

# 3
plot(0, xlab = parse(text = sprintf("'%s' ~ 2^-dCT", value)))

# 4
fo <- value ~ 2^-dCT
fo[[2]] <- as.name(value)
plot(0, xlab = fo)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341