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!
CodePudding user response:
We could use substitute
:
VT1PPO_CAD <- 96.32
plot(1:5,
main = substitute(paste(VT[1],": ", value1, "%"),
list(value1 = round(VT1PPO_CAD, 0))
)
)
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))
)
)
CodePudding user response:
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”.