r - 在R中使用lm和nls进行正弦曲线拟合

标签 r curve-fitting

我是曲线拟合的初学者,Stackoverflow上的几篇文章确实对我有所帮助。

我尝试使用lmnls将正弦曲线拟合到我的数据,但是两种方法都显示出奇怪的拟合,如下所示。谁能指出我哪里出了问题。我会怀疑与时间有关,但无法正确处理。可以从here访问我的数据。

data <- read.table(file="900days.txt", header=TRUE, sep="")
time<-data$time
temperature<-data$temperature

#lm fitting
xc<-cos(2*pi*time/366)
xs<-sin(2*pi*time/366)
fit.lm<-lm(temperature~xc+xs)
summary(fit.lm)
plot(temp~time, data=data, xlim=c(1, 900))
par(new=TRUE)
plot(fit.lm$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n",
yaxt="n")

#nls fitting
fit.nls<-nls(temp~C+alpha*sin(W*time+phi),
   start=list(C=27.63415, alpha=27.886, W=0.0652, phi=14.9286))
summary(fit.nls)
plot(fit.nls$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n", 
axt="n")

最佳答案

这是因为从数据中删除了NA值以使其适合(并且您的数据中有很多);因此,当您绘制fit.lm$fitted时,plot方法会将该系列的索引解释为“x”值以对其进行绘制。

试试这个[注意如何更改变量名以防止与timedata函数冲突(请阅读this帖子)]:

Data <- read.table(file="900days.txt", header=TRUE, sep="")
Time <- Data$time 
temperature <- Data$temperature

xc<-cos(2*pi*Time/366)
xs<-sin(2*pi*Time/366)
fit.lm <- lm(temperature~xc+xs)

# access the fitted series (for plotting)
fit <- fitted(fit.lm)  

# find predictions for original time series
pred <- predict(fit.lm, newdata=data.frame(Time=Time))    

plot(temperature ~ Time, data= Data, xlim=c(1, 900))
lines(fit, col="red")
lines(Time, pred, col="blue")

这给了我:

这可能正是您所希望的。

关于r - 在R中使用lm和nls进行正弦曲线拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104680/

相关文章:

r - 为什么 R 在学习过程中传递命令 (knn.pred=knn(train.X,test.X,train.Y,k=1)) 时抛出错误(无法找到函数 "knn")?

r - 为什么不建议在 R 中使用 attach(),我应该使用什么?

r - 检查 CRAN 传入的可行性...注意维护者

python - 拟合高斯函数

python - 将数据拟合到后处理非线性模型时,curve_fit 的算法是什么?

python - 无法对 3 段进行分段 numpy

r - 在R中,合并两个数据框,填充空白

linux - 在 Linux : Output Issues 上以批处理模式运行 R

python - 洛伦兹拟合两种编写代码的方式

r - Bass模型遗传算法的R实现