Sine curve fit using lm and nls in R

后端 未结 4 1461
自闭症患者
自闭症患者 2020-12-30 09:42

I am a beginner in curve fitting and several posts on Stackoverflow really helped me.

I tried to fit a sine curve to my data using lm and nls

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 10:09

    This is because the NA values are removed from the data to be fit (and your data has quite a few of them); hence, when you plot fit.lm$fitted the plot method is interpreting the index of that series as the 'x' values to plot it against.

    Try this [note how I've changed variable names to prevent conflicts with the functions time and data (read this post)]:

    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")
    

    This gives me:

    enter image description here

    Which is probably what you were hoping for.

提交回复
热议问题