String bquote:如何包含保存为字符串对象的表达式?

String bquote:如何包含保存为字符串对象的表达式?,string,r,expression,String,R,Expression,我的目标是用最佳拟合线的坡度注释绘图,并标记坡度单位,其中标签保存为单独的字符串对象。我很难弄清楚如何让bquote()将字符串对象转换为表达式,并将其与其他求值语句组合 示范: # example data: x <- c(1:20) # x units: time y <- x * rnorm(20, 10, 2) # y units: length per time unit.label <- "L%.%T^-2"

我的目标是用最佳拟合线的坡度注释绘图,并标记坡度单位,其中标签保存为单独的字符串对象。我很难弄清楚如何让
bquote()
将字符串对象转换为表达式,并将其与其他求值语句组合

示范:

# example data:
x <- c(1:20)                   # x units: time
y <-  x * rnorm(20, 10, 2)     # y units: length per time

unit.label <- "L%.%T^-2"       # label for slope of best fit line 
lm1 <- summary(lm(y ~ x))

plot(y ~ x)
我还可以获取
bquote()
以显示坡度的单位:

plot(y ~ x)
text(median(x), min(y), bquote(.(parse(text = unit.label))) )
但我无法将标签和坡度组合成一个
bquote()
语句:

plot(y ~ x)
text(median(x), min(y), bquote(slope: .(round(lm1$coefficients[2], 2)) 
.(parse(text = unit.label))) ) 
# Error: unexpected symbol in "text(median(x), min(y), bquote(slope: 
# .(round(lm1$coefficients[2], 2)) ."
使用
paste()
,单位标签将与坡度一起显示,但标签不会作为表达式读取:

plot(y ~ x)
text(median(x), min(y), bquote(slope: .(paste(round(lm1$coefficients[2], 2), 
as.expression(unit.label))))
)
我哪里做错了?这是我的bquote命令中的一个简单语法问题吗? 谢谢你的建议

1)解析字符字符串创建所需的字符串(确保它表示在R中语法有效的表达式),然后解析它。这里的
main\s
是字符串:

fm <- lm(y ~ x)

main_s <- paste("slope:", round(coef(fm)[2], 2), "~", unit.label)
plot(0, main = parse(text = main_s))
2)bquote上述方法可能是处理此问题最直接的方法,但要使用
bquote
请在
unit的位置尝试此方法。label_c
是调用对象,
fm
如上所述:

unit.label_c <- parse(text = unit.label)[[1]]
plot(0, main = bquote(slope: .(round(coef(fm)[2], 2)) ~ .(unit.label_c)))

unit.label\u c我喜欢首先使用
substitute
构建表达式,并且从不将部分表达式存储为字符向量。这会奏效的

plotlabel = substitute( slope~L%.%T^-2, 
    list(slope=round(lm1$coefficients[2], 2)))
plot(y ~ x)
text(median(x), min(y), plotlabel)
但是关于为什么
bquote
不起作用是一个有趣的问题。显然,您尝试替换的两种类型的对象是不同的类。在斜率值的情况下,这是一个基本字符,在unit.label的情况下,您调用的是parse,它返回一个表达式。在我看来,将表达式放入
bquote
似乎很棘手。奇怪的是,它完全是自己工作的

bquote(.(parse(text = unit.label))) #works -> expresion
bquote(.(parse(text = unit.label))+1) #doesn't work -> call

前者返回“表达式”,后者返回“调用”。实际上,我们希望第二个函数也返回一个表达式,但它试图将“+1”添加到已通过解析返回的表达式中,这似乎不太管用。

+1用于遵循post指南并使用可复制的示例。欢迎来到堆栈溢出!好问题。
plotlabel = substitute( slope~L%.%T^-2, 
    list(slope=round(lm1$coefficients[2], 2)))
plot(y ~ x)
text(median(x), min(y), plotlabel)
bquote(.(parse(text = unit.label))) #works -> expresion
bquote(.(parse(text = unit.label))+1) #doesn't work -> call