0

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))
    
Dave2e
  • 22,192
  • 18
  • 42
  • 50
Toy L
  • 55
  • 6

1 Answers1

0

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
Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Hello Dave2e, great. This answers the first part of my question. I do not understand however, how you got your `model: mi ~ a + Location^b`? – Toy L Aug 19 '21 at 19:47
  • You need to define an equation for `nls()` to fit. Since I had no prior knowledge of what this data is suppose to respresent, I randomly chose the exponential a*x^b. You may have other expectations and need create another equation that would better suit your data. – Dave2e Aug 19 '21 at 21:49
  • Thank you, Dave2e. Just to be clear you chose arbitrary coefficient values for a and b? – Toy L Aug 24 '21 at 20:03
  • Yes, the model and the starting values for a & b were arbitrary. – Dave2e Aug 24 '21 at 21:59
  • Would it be suggested that I post my second question in this post as a new post? – Toy L Aug 25 '21 at 03:10
  • 1
    It would be best to post a new question. – Dave2e Aug 25 '21 at 03:19