4

We can use subscript or superscript in a plot title in R using the following

plot(1,1, main=expression('title'^2))  #superscript

plot(1,1, main=expression('title'[2])) #subscript

However, what if I want to use a string variable in expression. For example,

my_string="'title'^2"

plot(1,1, main=expression(my_string))

Clearly, this doesn't work and the plot title just becomes my_string rather than title^2.

Is it possible to use a string variable inside expression?

Thanks, Brij.

1 Answer 1

0

In order to make an expression from a string, you need to parse it. Try this

my_string <- "'title'^2"
my_title <- parse(text=my_string)
plot(1,1, main=my_title)

If you just wanted to swap out certain parts of the expression with a string value, you can use something like bquote

my_string <- "title"
my_title <- bquote(.(my_string)^2)
plot(1,1, main=my_title)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. This seems to work. But it appears if I use my_string <- "'my title'^2", then the space between my and title confuses parse.
I cannot reproduce that problem. parse(text=my_string) with the my_string you provided works just fine for me. Are you sure your inner string is in quotes?
I had an additional step in my code and I figured it out. Thank you for your time and help. Much appreciated.
How to get 2 as some variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.