【问题标题】:Fitting raw data to difference equation using R使用 R 将原始数据拟合到差分方程
【发布时间】:2021-06-27 14:18:46
【问题描述】:

我正在尝试使用以下等式将模型拟合到数据集。

C[n] = C[n-1]+Ces*((1-C[n-1])/(1-C[n-1]*p))

数据集如下所示:。 空心圆圈是数据,红线是我希望使用某种曲线拟合程序实现的目标。数据中的第一个值可用于表示C[[1]],我正在寻找解决CCesp 的问题。我已经包含了一个原始数据示例和一些对其建模的代码(如上图所示)。我已经使用 R 中的 nls 包进行指数拟合,但这有点不同,我无法弄清楚如何最好地运行它。

C<-c(-0.003, 0.072, 0.149, 0.239, 0.320, 0.413, 0.456, 0.526, 0.554, 
0.611, 0.632, 0.648, 0.703, 0.714, 0.725, 0.771, 0.801, 0.770, 0.787,
 0.809, 0.836, 0.871, 0.866, 0.861, 0.873, 0.891, 0.887, 0.895, 
0.919, 0.930, 0.924, 0.927, 0.939, 0.929, 0.977, 0.929, 0.948, 0.944, 
0.947, 0.990, 0.981, 0.967, 0.973, 0.970, 1.005, 1.002, 0.978, 0.997, 
1.001, 1.008, 1.008, 1.016, 0.989, 1.037, 1.001, 1.030, 1.032, 0.999, 
1.031, 1.007, 1.015, 1.018)
Ces<-0.09
p<-0.01
Cd<-C[1]
Ce<-c(Cd)
I<-2
for (I in 2:length(C)) {
    Ct<-Cd+Ces*((1-Cd)/(1-Cd*p))
    Ce<-append(Ce, Ct)
    Cd<-Ct
}
summary(lm(C ~ Ce))$coefficients
plot(C, ylim=c(-0.5,1))
par(new=TRUE)
plot(Ce, type="l", col="red", ylim=c(-0.5,1))

【问题讨论】:

    标签: r curve-fitting differential-equations


    【解决方案1】:

    要使用nls,你需要将你的代码变成一个函数,但首先要保存你原来的适合:

    Ce.orig <- Ce   # The fit from your code
    satcurve <- function(C, Ces, p) {
        Cd<-C[1]
        Ce <- C[1]
        for (I in 2:length(C)) {
            Ct<-Cd+Ces*((1-Cd)/(1-Cd*p))
            Ce<-append(Ce, Ct)
            Cd<-Ct
        }
        return(Ce)
    }
    

    现在我们可以尝试改进您的原始值:

    fit <- nls(C~satcurve(C, Ces, p), start=list(Ces= -0.09, p= 0.01))
    summary(fit)
    # 
    # Formula: C ~ satcurve(C, Ces, p)
    # 
    # Parameters:
    #      Estimate Std. Error t value Pr(>|t|)    
    # Ces  0.100160   0.003492  28.682  < 2e-16 ***
    # p   -0.251757   0.087765  -2.869  0.00568 ** 
    # ---
    # Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    # 
    # Residual standard error: 0.01999 on 60 degrees of freedom
    # 
    # Number of iterations to convergence: 12 
    # Achieved convergence tolerance: 3.149e-06
    C.fit <- predict(fit)
    

    参数略有变化,符号反转。现在绘制结果。差别很小:

    plot(C)
    lines(Ce.orig, col="red")
    lines(C.fit, col="blue")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2015-03-09
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2018-02-19
      • 2020-06-04
      相关资源
      最近更新 更多