在表达式中使用字符串变量为R代表下标/上标

时间:2022-12-19 19:31:18

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

我们可以使用下面的R中的图标题使用下标或上标

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.

显然,这不起作用,情节标题只是成为my_string而不是标题^ 2。

Is it possible to use a string variable inside expression?

是否可以在表达式中使用字符串变量?

Thanks, Brij.

1 个解决方案

#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

如果你只是想用字符串值替换表达式的某些部分,你可以使用像bquote这样的东西

my_string <- "title"
my_title <- bquote(.(my_string)^2)
plot(1,1, main=my_title)

#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

如果你只是想用字符串值替换表达式的某些部分,你可以使用像bquote这样的东西

my_string <- "title"
my_title <- bquote(.(my_string)^2)
plot(1,1, main=my_title)