Automatic curve fitting in R

后端 未结 3 1372
旧时难觅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 20:58

    Try this. rhs is a character vector of right sides and x and y are the data. It constructs the formula fo for each and then extracts the parameters and sets each to 1 for the starting value. Finally it runs nls and returns the SSEs sorted so that the result is a vector of SSE's named via the right hand sides. If verbose=TRUE (which it is by default) then it also displays the output from each fit.

    sse <- function(rhs, x, y) sort(sapply(rhs, function(rhs, x, y, verbose = TRUE) {
        fo <- as.formula(paste("y", rhs, sep = "~"))
        nms <- setdiff(all.vars(fo), c("x", "y"))
        start <- as.list(setNames(rep(1, length(nms)), nms))
        fm <- nls(fo, data.frame(x, y), start = start)
        if (verbose) { print(fm); cat("---\n") }
        deviance(fm)
    }, x = x, y = y))
    
    ## test
    
    set.seed(123)
    x <- 1:10
    y <- rnorm(10, x)
    
    # modify to suit
    rhs <- c("a*x+b", "a*x*x+b*x+c")
    
    sse(rhs, x, y)
    

提交回复
热议问题