微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将非线性函数拟合到R中矩阵的时间序列

如何解决如何将非线性函数拟合到R中矩阵的时间序列

我在理解如何编写函数以及从R中的矩阵提取参数方面有些麻烦。这类似于Non linear fit in r 但是我还没有弄清楚。

作为示例,我已经使用线性拟合从相同的数据中提取y截距和斜率,并将它们用作矩阵中的新列:

library(tidyverse)
library(lazyeval)

design.mat <- cbind(1,c(340,340.33,340.66,341,342,343,346,349,352,355,358,368,378,388,398)) #design matrix with x values of time points
response.mat <- t(ts_rw[,36:50]) # transform rows to columns and select relevant points
reg <- lm.fit(design.mat,response.mat)$coefficients #linear fit to time points,extract intercept and slope (coefficients)
ts_rw <- cbind(ts_rw,t(reg)) #re-transform (intercept and slope for each row are added in new columns)

其中ts_rw是一个大的行矩阵,每列是一个时间点,每行是一个单独的

head(ts_rw)
individual X2      X3      X4      X5     X6     X7     X8     X9    X10    X11    X12    X13    X14    X15    X16    X17    X18
1      <NA>  0 0.77150 1.17260 1.62550 2.6667 3.0663 3.2323 3.3331 3.4293 3.5010 3.6000 3.6099 3.6941 4.1558 4.2500 4.3215 4.3215
2  PI665092  0 0.71872 1.00040 1.25040 1.9385 2.3136 2.5397 2.7147 2.8328 2.9164 3.0014 3.0828 3.1824 3.6377 3.7900 3.9024 4.0000
3  PI665092  0 0.58076 0.84209 1.03010 2.0000 2.6109 2.9331 3.1266 3.2663 3.3763 3.4662 3.5404 3.6437 4.0007 4.0794 4.1032 4.0828

具有更多的行和列。

作为简化的数据,请关注列:

timepoints <- c(340,398)
row2 <- as.numeric(as.vector(ts_rw[2,36:50]))
row3 <- as.numeric(as.vector(ts_rw[3,36:50]))

print(timepoints)
[1] 340.00 340.33 340.66 341.00 342.00 343.00 346.00 349.00 352.00 355.00 358.00 368.00 378.00 388.00 398.00
print(row2)
 [1] 3.56900 1.69690 1.35020 1.19020 0.96450 0.86805 0.77572 0.75023 0.82184 0.85174 0.84638 0.84638 0.78600 0.74063 0.71467
print(row3)
 [1] 5.5473 3.6941 3.3142 3.1771 2.7650 2.6260 2.4220 2.4710 2.6328 2.6328 2.5301 2.5301 2.4710 2.4748 2.4443

非线性拟合的函数是:

值= a *(exp(-b *时间))+ c

我想用它代替lm.fit,以便为每个人提取a,b和c。有什么想法可以做到这一点吗?谢谢。

-更新

我认为麻烦在于实现正确的起始值。如果我尝试这样的话:

x <- c(340,398)
y <- as.numeric(as.vector(ts_rw[2,36:50]))

df <- data.frame(x,y)
print(df)
        x       y
1  340.00 3.56900
2  340.33 1.69690
3  340.66 1.35020
4  341.00 1.19020
5  342.00 0.96450
6  343.00 0.86805
7  346.00 0.77572
8  349.00 0.75023
9  352.00 0.82184
10 355.00 0.85174
11 358.00 0.84638
12 368.00 0.84638
13 378.00 0.78600
14 388.00 0.74063
15 398.00 0.71467

m <- nls(y ~ I(a*(exp(-b*x))+c),data=df,start=list(a=max(y),b=6.4,c=0.8),alg="plinear",trace=T)
y_est<-predict(m,df$x)
plot(x,y)
lines(x,y_est)
summary(m)

this question一样尝试计算系数a,b和c的估计值

summary(m)
Error in chol2inv(object$m$Rmat()) : 
  element (2,2) is zero,so the inverse cannot be computed

合身无法正常工作

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。