gpt4 book ai didi

string - bquote : How to include an expression saved as a string object?

转载 作者:行者123 更新时间:2023-12-04 23:01:06 24 4
gpt4 key购买 nike

我的目标是用最佳拟合线的斜率注释绘图并标记斜率的单位,其中标签保存为单独的字符串对象。我不知道如何获得 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() 来显示斜率:
text(median(x), min(y), bquote(slope: .(round(lm1$coefficients[2], 2))) )

我也可以得到 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))

语句设置 main_s也可以替换为以下 sprintf可以说更具可读性的语句:
main_s <- sprintf("slope: %.2f ~ %s", coef(fm)[2], unit.label)

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)))

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

screenshot

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

关于string - bquote : How to include an expression saved as a string object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com