0

I have a novice question: with this code section, I would like to put the 1 of VT1 as subscript.

[...]
  annotate("text", x=VT1PPO_CAD-2, y=40,   ##or bp_CAD if we use absVO2%
           label=paste0("VT1: ", round(VT1PPO_CAD, 0), "%"), angle=90, size = 4) +
[...]

I have tried this but it does not work.

label=paste0(expression(paste("V", T[1], ": ")), round(VT1PPO_CAD, 0), "%")

Thank you very much!

zx8754
  • 52,746
  • 12
  • 114
  • 209
MaxB
  • 139
  • 8
  • 1
    Please provide a complete example including the code, inputs and library statement so that others can actually run it using copy and paste from the question. See the top of the [tag:r] tag page for posting guidance. – G. Grothendieck Jan 19 '23 at 10:45
  • 1
    Possible duplicate: https://stackoverflow.com/q/67857985/680068 and https://stackoverflow.com/q/9723239/680068 – zx8754 Jan 19 '23 at 10:51
  • This two posts are for superscript of R squared. Mine is for subscript. – MaxB Jan 19 '23 at 10:55

2 Answers2

1

The fundamental issue with your attempted solution is that that your entire label needs to be an unevaluated expression if you want R to format it properly. Your code attempts to use the unevaluated expression as part of a character string (the outer paste0 call converts the arguments to strings). This does not work.

So instead you need to invert the logic: you need to create an unevaluated expression, and you need to interpolate your variable (VT1PPO_CAD) into that expression (after rounding).

The expression function does not allow interpolating values1. To interpolate (= insert evaluated) subexpressions, you need to use another solution. Several exist, but my favourite way in base R is the bquote function.

Furthermore, there’s no need to split and/or quote V and T; just put them adjacent:

bquote(paste(VT[1], ": ", .(round(VT1PPO_CAD, 0)), "%"))

bquote accepts an expression and evaluates sub-expressions that are wrapped in .(…) before inserting the result of the evaluation into the surrounding expression.


1 In general the expression function is completely useless, I have no idea why it even exists; as far as I can tell it’s 100% redundant with quote. The answer is probably “for compatibility with S”.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

We could use substitute:

VT1PPO_CAD <- 96.32

plot(1:5,
     main = substitute(paste(VT[1],": ", value1, "%"),
                       list(value1 = round(VT1PPO_CAD, 0))
                       )
     )   

enter image description here

Or ggplot2 (as per your tag):

library(tibble)
library(ggplot2)

tibble(x = 1:5, y = 1:5) |>
  ggplot(aes(x, y)) +
  geom_point() +
  labs(title = substitute(paste(VT[1],": ", value1, "%"),
                         list(value1 = round(VT1PPO_CAD, 0))
                          )
        )

enter image description here

harre
  • 7,081
  • 2
  • 16
  • 28