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

Tro*_*roy 5 string expression r

我的目标是用最佳拟合线的斜率注释绘图并标记斜率的单位,其中标签保存为单独的字符串对象。我无法弄清楚如何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)
Run Code Online (Sandbox Code Playgroud)

当我尝试注释情节时会出现问题。我可以得到 bquote() 来显示斜率:

text(median(x), min(y), bquote(slope: .(round(lm1$coefficients[2], 2))) )
Run Code Online (Sandbox Code Playgroud)

我还可以bquote()显示斜率的单位:

plot(y ~ x)
text(median(x), min(y), bquote(.(parse(text = unit.label))) )
Run Code Online (Sandbox Code Playgroud)

但我无法将标签和斜率合并为一个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)) ."
Run Code Online (Sandbox Code Playgroud)

使用paste(),单位标签与斜率一起出现,但标签不被视为表达式:

plot(y ~ x)
text(median(x), min(y), bquote(slope: .(paste(round(lm1$coefficients[2], 2), 
as.expression(unit.label))))
)
Run Code Online (Sandbox Code Playgroud)

我哪里错了?这是我的 bquote 命令中的简单语法问题吗?感谢您的任何建议!

G. *_*eck 5

1) parse char string创建所需的字符串(确保它表示在 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))
Run Code Online (Sandbox Code Playgroud)

语句设置main_s也可以替换为以下sprintf语句,这可以说是更具可读性:

main_s <- sprintf("slope: %.2f ~ %s", coef(fm)[2], unit.label)
Run Code Online (Sandbox Code Playgroud)

2) bquote上面可能是处理这个问题的最直接的方法,但是要使用bquotetry this whereunit.label_c是一个调用对象,并且fm定义如上:

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

在任何一种情况下,我们都会得到:

截屏

更新已添加 (2)。还有一些改进和更正。