在R中使用lm和nls拟合正弦曲线

Edd*_*die 8 r curve-fitting

我是曲线拟合的初学者,Stackoverflow上的几个帖子对我很有帮助.

我尝试使用正弦曲线拟合我的数据lm,nls但两种方法都显示出一种奇怪的拟合,如下所示.谁能指出我哪里出错了.我怀疑与时间有关,但无法做到正确.我的数据可以从这里访问. 情节

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")
Run Code Online (Sandbox Code Playgroud)

And*_*our 10

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

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

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")
Run Code Online (Sandbox Code Playgroud)

这给了我:

在此输入图像描述

这可能是你所希望的.