作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的目标是用最佳拟合线的斜率注释绘图并标记斜率的单位,其中标签保存为单独的字符串对象。我不知道如何获得 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)
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))))
)
最佳答案
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)
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)))
关于string - bquote : How to include an expression saved as a string object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130448/
我是一名优秀的程序员,十分优秀!