gpt4 book ai didi

r - R中的幂回归类似于excel

转载 作者:行者123 更新时间:2023-12-04 02:42:07 26 4
gpt4 key购买 nike

我有一个简单的数据集,我正在尝试使用功率趋势来最好地拟合数据。样本数据很小,如下:

structure(list(Discharge = c(250, 300, 500, 700, 900), Downstream = c(0.3, 
0.3, 0.3, 0.3, 0.3), Age = c(1.32026239202165, 1.08595138888889,
0.638899189814815, 0.455364583333333, 0.355935185185185)), .Names = c("Discharge",
"Downstream", "Age"), row.names = c(NA, 5L), class = "data.frame")

数据如下所示:
> new
Discharge Downstream Age
1 250 0.3 1.3202624
2 300 0.3 1.0859514
3 500 0.3 0.6388992
4 700 0.3 0.4553646
5 900 0.3 0.3559352

我尝试使用 ggplot2 绘制上述数据
ggplot(new)+geom_point(aes(x=Discharge,y=Age))

我可以使用 geom_smooth(method="lm") 添加线性线但我不确定我需要什么代码来显示电源线。

输出如下:

enter image description here

如何像在 excel 中所做的那样添加幂线性回归线? excel图如下所示:

enter image description here

最佳答案

使用 nls (非线性最小二乘法)作为您的平滑器

例如

ggplot(DD,aes(x = Discharge,y = Age)) +
geom_point() +
stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE)

注意到 Doug Bates 对 R 平方值和非线性模型的评论 here ,你可以使用这些想法
Adding Regression Line Equation and R2 on graph

追加回归线方程
# note that you have to give it sensible starting values
# and I haven't worked out why the values passed to geom_smooth work!
power_eqn = function(df, start = list(a =300,b=1)){
m = nls(Discharge ~ a*Age^b, start = start, data = df);
eq <- substitute(italic(y) == a ~italic(x)^b,
list(a = format(coef(m)[1], digits = 2),
b = format(coef(m)[2], digits = 2)))
as.character(as.expression(eq));
}

ggplot(DD,aes(x = Discharge,y = Age)) +
geom_point() +
stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE) +
geom_text(x = 600, y = 1, label = power_eqn(DD), parse = TRUE)

关于r - R中的幂回归类似于excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18305852/

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