gpt4 book ai didi

r - 在ggplot中存在非线性回归问题

转载 作者:行者123 更新时间:2023-12-04 11:51:41 25 4
gpt4 key购买 nike

attenuation = data.frame(km =      
c(0,0,0.4,0.4,0.8,0.8,1.2,1.2,1.6,1.6,2,2,2.4,2.4,2.8,2.8,3.2,3.2,3.6,3.6,4,
4,4.4,4.4,4.8,4.8,5.2,5.2,5.6,5.6,6,6,6.4,6.4,6.8,6.8,7.2,7.2,7.6,7.6,8,8,
11.7,11.7,13,13), edna = c(76000,20000,0,0,6000,0,0,6880,10700,0,6000,
0,0,0,0,0,0,6000,0,0,0,0,0,0,0,0,6310,0,6000,6000,0,0,0,0,0,
0,0,0,0,0,0,6000,0,0,0,0))

#This worked great for a linear regression
ggplot(attenuation, aes(x = km, y = edna)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE) +
xlab("Distance from Cage (km)") +
ylab("eDNA concentration (gene sequence/Liter)")

但线性回归似乎不太适合(r 平方 =0.09)。所以我想试试别的。我尝试了其他一些拟合不佳的回归,所以我想尝试非线性回归。

我研究了这个关于堆栈溢出的问题,并尝试了许多不同的选项,但没有任何效果。我在下面提供的选项最有意义 - 但我想知道我的公式是否错误?或者如果需要修改开始列表?

对于上下文,我试图探索河流距离和浓度之间的关系。

#This is not working for a nonlinear regression
ggplot(attenuation, aes(x = km, y = edna))+
geom_point() +
stat_smooth(method = 'nls', formula = 'y~a*x^b', method.args=list (start =
list(a = 1,b=1), se=FALSE))

当我运行上面的 nls 代码时,我从 r 收到以下错误 stat_smooth() 中的计算失败: 可变长度不同(为 '(se)' 找到)

最佳答案

你有两个问题。首先是一个放错位置的“)”,因为 se=FALSEstat_smooth= 的参数,而不是 method.args=:

ggplot(attenuation, aes(x = km, y = edna))+ 
geom_point() +
stat_smooth(method='nls', formula='y~a*x^b', method.args=list(start =
list(a=1, b=1)), se=FALSE)

但这也行不通,因为您的模型不可能适合您的数据。看方程。当 x=0 时,y 将等于 0。对于 x 大于 0 的值,除非 b 为负数,否则 y 将增加,但随后 x=0 为 Inf,因此算法无法尝试负值。由于您具有递减关系,因此您需要指定为 x=0 和合理的起始值定义的函数。这个参数比线性函数更适合您的数据(它也可以定义为 a*(x + 1)^-1 这本质上是您的函数,将 1 添加到 x 以便定义在 x=0:

ggplot(attenuation, aes(x = km, y = edna))+ 
geom_point() +
stat_smooth(method = 'nls', formula = 'y~a/(x + 1)',
method.args=list(start=list(a=50000)), se=FALSE)

[ One parameter[1]

我通过拆分 20,000 和 76,000 之间的差额选择了 50000。最终估计约为20,000。您可以通过添加第二个参数来更大幅度地弯曲曲线,但是您的 0 值太多了,这可能太多了,具体取决于您要传达的内容:

ggplot(attenuation, aes(x = km, y = edna))+ 
geom_point() +
stat_smooth(method='nls', formula='y~a*(1+x)^b', method.args=list(start =
list(a=50000, b=-1)), se=FALSE)

Two parameters

关于r - 在ggplot中存在非线性回归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753823/

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