Automatic curve fitting in R

后端 未结 3 1374
旧时难觅i
旧时难觅i 2021-02-04 20:17

Is there any package that automatically fits a curve using many simple models?
By simple models I mean:

  • ax+b
  • ax^2+bx+c
  • a*log(x) + b
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 21:02

    You can fit a Regression Splines and find a good fit by manually adjusting the degrees of freedom a few times. Try the following function:

    spline.fit <- function(x, y, df=5) {
      ## INPUT: x, y are two vectors (predictor and response);
      ##        df is the number of spline basis.  Increase "df" to fit more adaptively to the data.
      require(splines) # available as default R Package.
      bx <- bs(x, df)  # B-spline basis matrix as New Predictors (dimension is "length(x)" by "df")
      f <- lm(y ~ bx)  # Linear Regression on Spline Basis (that is, "df" number of new predictors)
      fy <- fitted(f)  # Fitted Response
      plot(x, y); lines(x, fy, col="blue", lwd=2) # Make a plot to show the fit.
      invisible(list(x=bx, y=fy, f=f))    # Return the Basis (new predictors), Fitted Y, Regression
    }
    
    if (F) {                                # Unit Test
      spline.fit(1:100, rnorm(100))
      spline.fit(1:100, rnorm(100), df=20)
    }
    

提交回复
热议问题