Amm*_*Amm 5 statistics regression r linear-regression ggplot2
我有一个数据框x1,它是用以下代码生成的,
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)
Run Code Online (Sandbox Code Playgroud)
我想提取y轴截距和数据的线性回归拟合斜率,
x y z s t q
1 1 1 -19 -6.333333 -38 -6.333333
2 2 8 -12 -4.000000 -24 -32.000000
3 3 27 7 2.333333 14 63.000000
4 4 64 44 14.666667 88 938.666667
5 5 125 105 35.000000 210 4375.000000
6 6 216 196 65.333333 392 14112.000000
7 7 343 323 107.666667 646 36929.666667
8 8 512 492 164.000000 984 83968.000000
9 9 729 709 236.333333 1418 172287.000000
10 10 1000 980 326.666667 1960 326666.666667
Run Code Online (Sandbox Code Playgroud)
我使用以下代码融化并绘制三列数据,
xm <- melt(x1, id=names(x1)[1], measure=names(x1)[c(2, 4, 5)], variable = "cols")
plt <- ggplot(xm) +
geom_point(aes(x=x,y= value, color=cols), size=3) +
labs(x = "x", y = "y")
Run Code Online (Sandbox Code Playgroud)

现在,我需要的是分别获取所有数据的线性最小二乘拟合,并将所得的截距和斜率存储在新的数据框中。
我使用plt + geom_abline()但没有得到想要的结果。有人可以让我知道如何解决这个问题。
我想你正在寻找geom_smooth。如果您使用参数 调用此函数method = "lm",它将计算所有组的线性拟合:
ggplot(xm, aes(x = x, y = value, color = cols)) +
geom_point(size = 3) +
labs(x = "x", y = "y") +
geom_smooth(method = "lm", se = FALSE)
Run Code Online (Sandbox Code Playgroud)

poly您还可以使用函数和参数指定二次拟合formula:
ggplot(xm, aes(x = x, y = value, color=cols)) +
geom_point(size = 3) +
labs(x = "x", y = "y") +
geom_smooth(method = "lm", se = FALSE, formula = y ~ poly(x, 2))
Run Code Online (Sandbox Code Playgroud)

要提取相应的回归系数,可以使用以下方法:
# create a list of coefficients
fits <- by(xm[-2], xm$cols, function(i) coef(lm(value ~ x, i)))
# create a data frame
data.frame(cols = names(fits), do.call(rbind, fits))
# cols X.Intercept. x
# y y -277.20000 105.40000
# s s -99.06667 35.13333
# t t -594.40000 210.80000
Run Code Online (Sandbox Code Playgroud)
如果您想要二次拟合,只需替换value ~ x为value ~ poly(x, 2)。