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!