How to put a complicated equation into a R formula?

前端 未结 3 819
谎友^
谎友^ 2020-12-16 19:13

We have the diameter of trees as the predictor and tree height as the dependent variable. A number of different equations exist for this kind of data and we try to model som

3条回答
  •  时光取名叫无心
    2020-12-16 19:58

    Assuming you are using nls the R formula can use an ordinary R function, H(a, b, c, D), so the formula can be just h ~ H(a, b, c, dbh) and this works:

    # use lm to get startingf values
    lm1 <- lm(1/(h - 1.3) ~ I(1/dbh) + I(1/dbh^2), df)
    start <- rev(setNames(coef(lm1), c("c", "b", "a")))
    
    # run nls
    H <- function(a, b, c, D) 1.3 + D^2 / (a + b * D + c * D^2)
    nls1 <- nls(h ~ H(a, b, c, dbh), df, start = start)
    
    nls1 # display result
    

    Graphing the output:

    plot(h ~ dbh, df)
    lines(fitted(nls1) ~ dbh, df)
    

    enter image description here

提交回复
热议问题