Home > front end >  How to add a styling argument from object in bquote?
How to add a styling argument from object in bquote?

Time:09-08

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?

CodePudding user response:

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])

CodePudding user response:

1) Another possibility is to use a string and then parse it at the end.

mstyle <- "bold"
var <- LETTERS[1:4]

s <- sprintf("%s(%s)", mstyle, var[1])  # "bold(A)"
plot(1)
text(1, 0.8, parse(text = s))

2) If the entire string is to be bold then we could use face = 2. In general plain is 1, bold is 2, italic is 3, bold-italic is 4 and symbol is 5.

face <- 2 # bold
plot(1)
text(1, 0.8, var[1], face = face)
  • Related