我使用以下代码行生成了一些数据
x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q <- s*y
x1 <- cbind(x,y,z,s,t,q)
x1 <- data.frame(x1)
我想绘制x与y,s和t的关系,所以我首先融合了数据框x1
,
library(reshape2)
xm <- melt(x1, id=names(x1)[1], measure=names(x1)[c(2, 4, 5)], variable = "cols"`)
然后我使用以下代码将它们与线性拟合一起绘制,
library(ggplot2)
plt <- ggplot(xm, aes(x = x, y = value, color = cols)) +
geom_point(size = 3) +
labs(x = "x", y = "y") +
geom_smooth(method = "lm", se = FALSE)
plt
生成的图如下所示,
现在我想插入线性拟合的 x-intercept 。图中y轴值为0的点。
如here所示的以下代码行提取斜率和y轴截距。
fits <- by(xm[-2], xm$cols, function(i) coef(lm(value ~ x, i)))
data.frame(cols = names(fits), do.call(rbind, fits))
除了从斜率和y轴截距手动计算外,有什么办法可以提取x截距吗?
感谢您的帮助!
答案 0 :(得分:3)
如果你不想自己计算,你可以在chemCal包中实现逆向预测:
library(chemCal)
res <- by(xm[-2], xm$cols, function(i) inverse.predict(lm(value ~ x, i), 0)$Prediction)
res[1:3]
#xm$cols
#y s t
#2.629981 2.819734 2.819734
修改强>
也许你更喜欢这个:
library(plyr)
res <- ddply(xm, .(cols),
function(i) data.frame(xinter=inverse.predict(lm(value ~ x, i), 0)$Prediction))
# cols xinter
# 1 y 2.629981
# 2 s 2.819734
# 3 t 2.819734
答案 1 :(得分:1)
我不认为你可以避免计算线性方程式,当然你不必手工完成(除非你想)。例如:
by(xm[-2], xm$cols, function(i) {
fit <- lm(value~x, i); print(fit); solve(coef(fit)[-1], -coef(fit)[1] )}
)
Call:
lm(formula = value ~ x, data = i)
Coefficients:
(Intercept) x
-277.2 105.4
Call:
lm(formula = value ~ x, data = i)
Coefficients:
(Intercept) x
-99.07 35.13
Call:
lm(formula = value ~ x, data = i)
Coefficients:
(Intercept) x
-594.4 210.8
xm$cols: y
[1] 2.629981
-----------------------------------------------------------------------------------------------------------------
xm$cols: s
[1] 2.819734
-----------------------------------------------------------------------------------------------------------------
xm$cols: t
[1] 2.819734
对于x - >,所解决的基本上是-277.2 + 105.4 * x = 0。 105.4 * x = 277.2(求解函数调用) - &gt; x = 2.629981。似乎你的线条&#39;并且&#39; t&#39;在同一点交叉y = 0轴。如果我理解正确,你的问题不是外推,因为你的x范围覆盖了截距,而是插值。
聚苯乙烯。我认为您的代码丢失了:require(&#34; reshape&#34;)
编辑:
result <- c(by(xm[-2], xm$cols, function(i) { fit <- lm(value~x, i); print(fit); solve(coef(fit)[-1], -coef(fit)[1] )} )); print(result)
> print(result)
y s t
2.629981 2.819734 2.819734
答案 2 :(得分:0)
我找到了一种计算x截距的方法,首先用y轴截距和斜率值创建一个数据框,
par <- data.frame(cols = names(fits), do.call(rbind, fits))
然后重命名列标题名称以准确表示值
colnames(par)[2] <- "y_intercept"
colnames(par)[3] <- "slope"
# Calculate the x-intercept by using the formula -(y_intercept)/slope
x_incpt <- -par[2]/par[3]
colnames(x_incpt) <- "x_intercept"
这给出了以下结果,
x_intercept
y 2.629981
s 2.819734
t 2.819734