【问题标题】:Using a string variable in expression for R for subscript/superscript在 R 的表达式中使用字符串变量作为下标/上标
【发布时间】:2018-11-23 08:03:55
【问题描述】:

我们可以使用以下方法在 R 中的绘图标题中使用下标或上标

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

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

但是,如果我想在表达式中使用字符串变量怎么办。例如,

my_string="'title'^2"

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

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

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

谢谢, 布里杰。

【问题讨论】:

    标签: r expression subscript superscript


    【解决方案1】:

    为了从字符串中生成表达式,您需要对其进行解析。试试这个

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

    如果你只是想用字符串值替换表达式的某些部分,你可以使用类似bquote

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

    【讨论】:

    • 谢谢。这似乎有效。但是如果我使用 my_string
    • 我无法重现该问题。 parse(text=my_string) 和您提供的 my_string 对我来说效果很好。你确定你的内部字符串在引号中吗?
    • 我的代码中有一个额外的步骤,我想通了。感谢您的时间和帮助。非常感谢。
    • 如何获取 2 作为变量?
    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2011-04-15
    • 2022-01-22
    相关资源
    最近更新 更多