Search code examples
rfunctioncurve-fittingpolynomialsnls

Smooth curve of a four parameter polynomial


I'm working with an nls model using this formula (b1 * ((b2 * x)^b4)) / (1 + ((b2 * x)^b4))^(b3 / b4)

I use nls2 package with a random algorithm to find the initial values. This my code for the function of formula and curve:

eqn <- function(x){(b1 * ((b2 * x)^b4)) / (1 + ((b2 * x)^b4))^(b3 / b4)}


curve(eqn, data$x, data$y, col = "green", n = 6)

I don't know, if I use n = "" properly. But, I use n = 6 as the length of the equation because my data have 6 values on x and y variables.

However, when I try to make a curve for the model, it ended up on an error: object 'b1' not found.

How can I avoid this error? I avoided this error by setting up an estimated values of the variables I get using nls2 outside the structure of nls2.

For example:

b1 = 1
b2 = 5
b3 = 0.7
b4 = 9.5

**On the other hand, how to set up the values of the variables inside the curve() for the equation without getting an error: object 'b1' not found., should I use start = list()?

curve(eqn, data$x, data$y, col = "green", n = 6, start = list (b1 = 1, b2 = 5, b3 = 0.7, b = 9.5))

I found various examples about making a curve for a polynomial equation, but those examples already have defined values for the variables of the equation. Is there a way to set up the variables using the estimated values calculated from the nls2?


Solution

  • You will need to define your equation to accept the coefficients b1 to b4 as inputs like this:

    eqn <- function(x, b1, b2, b3, b4){
             (b1 * ((b2 * x)^b4)) / (1 + ((b2 * x)^b4))^(b3 / b4)
           }
    

    The pass the coefficients to the calling function like this:

    curve(eqn(x, b1 = 1, b2 = 5, b3 = 0.7, b4 = 9.5), from=0, to=2, col = "green", n = 60)
    

    You need to define the starting and stopping values for x. Also select a value for "n" a large enough value for a smooth curve, n at 6 will not be smooth.