Search code examples
rcurve-fittingnls

Applying fitting data with nls


Hi and thank you in advance for any suggestions here! My question is using nls() how can I

  1. find the best optimal fit amongst the other fits-- ie linear and non linear-- for my data and

  2. show the fit on the ggplot graph below?

    library(ggplot2)
    library(mosiac)
    library(tidyverse)
    library(dplyr)
    
    # data frame
    FX <- data.frame(Location=c(1:5), mi=c(1, 4, 16, 16^2,256^2))
    
    #Visual
    ggplot(FX,aes(x=Location, y=mi))+
      geom_line(alpha=0.9, color="red")
    
    # nls(). It shows error of Error in nls(mi ~ Location, data = FX, start = list(mi = 1, 
    #Location = 1)) : 
    #no parameters to fit
    nls(mi~Location,data=FX,start=list(mi=1,Location=1))
    

Solution

  • You need to include adjustable parameters for your equation in the nls() function.

    FX <- data.frame(Location=c(1:5), mi=c(1, 4, 16, 16^2,256^2))
    
    nls(mi~a+Location^b, data=FX, start=list(a=1, b=4))
    
    # Nonlinear regression model
    # model: mi ~ a + Location^b
    # data: FX
    # a         b 
    # -3573.540     6.906 
    # residual sum-of-squares: 142513083
    # 
    # Number of iterations to convergence: 8 
    # Achieved convergence tolerance: 6.011e-06