Search code examples
rtextexpressionstyling

How to add a styling argument from object in bquote?


I'd like to add a formatted text to a plot using bquote like this:

var <- LETTERS[1:4]
eq <- bquote(bold(.(var[1])))
plot(1)
text(1,0.8,eq)

Actually, I want to set the styling argument (here: bold) from an object:

mstyle <- "bold"
var <- LETTERS[1:4]
eq <- bquote(.(mstyle)(.(var[1])))
plot(1)
text(1,0.8,eq)

This results in "bold(A)". I've tried multiple combinations of bquote, expression, substitute etc. but I can't get it work.

Any ideas?


Solution

  • It doesn't work because mstyle is a string rather than a symbol. Wrapping it in as.symbol() fixes this:

    eq <- bquote(.(as.symbol(mstyle))(.(var[1])))
    

    ... although there's no longer any point using bquote(). You might as well use call():

    eq <- call(mstyle, var[1])