我是曲线拟合的初学者,Stackoverflow上的几篇文章确实对我有所帮助。
我尝试使用lm
和nls
将正弦曲线拟合到我的数据,但是两种方法都显示出奇怪的拟合,如下所示。谁能指出我哪里出了问题。我会怀疑与时间有关,但无法正确处理。可以从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”值以对其进行绘制。
试试这个[注意如何更改变量名以防止与time
和data
函数冲突(请阅读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/