$ 运算符无效

  • 本文关键字:无效 运算符 r
  • 更新时间 :
  • 英文 :


我正在尝试绘制一条回归线,其中包含x和y中的一些数据。 我创建了一个计算直线系数的函数,然后在"p"中调用它以在标题中显示方程。

library(ggplot2)
x <- c(1,2,2,2,3,3,4,5,5,6,6,6,6,7,8,9,9,11,11,11,15,15,16,16,16,16,17,18,18,18)
y <- c(1,2,4,3,3,2,5,4,6,3,7,7,6,7,8,4,5,4,9,9,13,14,15,15,15,16,17,19,19,20)
eq = function(x) {
lm_coef <-list( a = round(coef(x)[2], digits = 2), b = round(coef(x)[1], digits = 2), r2 = round(summary(x)$r.squared, digits = 2));
lm_eq <- substitute(y =  a * x + b )
as.character(as.ep(lm_eq));
}
p <- ggplot(data=NULL, aes(x=x, y=y)) +
geom_point() +
geom_smooth(method=lm, se=FALSE, color="black") +
scale_y_log10() +
ggtitle(eq(x))+
theme(plot.title= element_text(hjust=0.5, size=20))
p

问题是我收到此错误消息:

"$ 运算符对原子向量无效"。

我知道问题来自我在ggtitle(equation(x))的电话,但我不知道如何解决。

如果你有一个想法,谢谢

我想你想要这样的东西:

library(ggplot2)
x <- c(1,2,2,2,3,3,4,5,5,6,6,6,6,7,8,9,9,11,11,11,15,15,16,16,16,16,17,18,18,18)
y <- c(1,2,4,3,3,2,5,4,6,3,7,7,6,7,8,4,5,4,9,9,13,14,15,15,15,16,17,19,19,20)
df = as.data.frame(cbind(x,y))
lm_eqn <- function(x,y){
m <- lm(y ~ x);
a = format(unname(coef(m)[1]), digits = 2)
b = format(unname(coef(m)[2]), digits = 2)
r2 = format(summary(m)$r.squared, digits = 3)
eq = paste("y = ", a, " + ",b, "* x", "   R² = ", r2)
as.character(as.expression(eq));
}
p <- ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
geom_smooth(method=lm, se=FALSE, color="black") +
scale_y_log10() +
ggtitle(lm_eqn(x,y))+
theme(plot.title= element_text(hjust=0.5, size=20))
p

但是,您还应该阅读上面的注释并了解代码中的错误。

最新更新