Using lm for Nonlinear Fitting in R

Source: Internet
Author: User

Previously, I only knew that lm functions in R can be used for linear fitting, just like the function name: LM = Linear Model

However, when we need to perform nonlinear fitting today, we need to search for various functions on the Internet, including NLS and NLM. However, NLM usage seems to be different from general modeling functions. NLS functions are similar in usage, but there is always an error and I don't know why. Once again, I suddenly found that the LM function can complete this job:

The essence of Lm function non-linear fitting is to add non-linear variables in it, linear fitting of these non-linear variables, the results are still non-linear.

Library (CAR) plot (uspop) lmfit = LM (population ~ Year, data = uspop) # linear fitting lines (uspop $ year, predict (lmfit) nlmfit1 = LM (population ~ I (year ^ 2) + year, data = uspop) # mark a square item year ^ 2 as a variable nlmfit1summary (nlmfit1) lines (uspop $ year, predict (nlmfit1), Col = 'red') # Nonlinear Fitting

In another example, I studied it myself:

Type_num = As. Numeric (type_fac) NLM = LM (gene_data ~ I (exp (-type_num) # wrap an exponential function in I to a variable of the linear fitting function lm # nlmsumm_nlm = Summary (NLM) summ_nlmnlm_pval = summ_nlm $ coefficients [2, 4] # lmfit_all = LM (gene_data ~ As. Numeric (as. Factor (type) summ_all = Summary (fit_all) lmpval_all = summ_all $ coefficients [2, 4] # Make plotplot (gene_data ~ (Type_fac), xlab = 'state', ylab = 'expression of expression', main = paste ('gene expression vs stage \ n ', 'Non Linear Model pval for stages = ', nlm_pval,' \ n Linear Model pval for stages = ', lmpval_all) points (gene_data ~ Type_fac) # Add fitted linesx = seq (. 5, 5.5 ,. 001) y = 17.2373 * exp (-x) + 7.8884 head (y) lines (x, y) # non linear liney2 = 15.7728-2.1422 * xlines (x, Y2) # linear line

We can see that the degree of Nonlinear fitting is better!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.