Search code examples
rcoefficient-of-determination

Calculating R^2 for a nonlinear least squares fit


Suppose I have x values, y values, and expected y values f (from some nonlinear best fit curve).

How can I compute coefficient of determination (R2)? Note that this function is not a linear model, but a nonlinear least squares (nls) fit, so not an lm fit.


Solution

  • You just use the lm function to fit a linear model:

    x = runif(100)
    y = runif(100)
    spam = summary(lm(x~y))
    > spam$r.squared
    [1] 0.0008532386
    

    Note that the r squared is not defined for non-linear models, or at least very tricky, quote from R-help:

    There is a good reason that an nls model fit in R does not provide r-squared - r-squared doesn't make sense for a general nls model.

    One way of thinking of r-squared is as a comparison of the residual sum of squares for the fitted model to the residual sum of squares for a trivial model that consists of a constant only. You cannot guarantee that this is a comparison of nested models when dealing with an nls model. If the models aren't nested this comparison is not terribly meaningful.

    So the answer is that you probably don't want to do this in the first place.

    If you want peer-reviewed evidence, see this article for example; it's not that you can't compute the R^2 value, it's just that it may not mean the same thing/have the same desirable properties as in the linear-model case.