❝本节来介绍如何使用R语言进行「nls」模型分析,通过两个案例进行介绍;代码过程很是简洁,各位观众老爷细细品味 ❞
library(tidyverse)
library(ggpmisc)
library(gginnards)
library(ggtext)
args <- list(formula = y ~ k * e ^ x,
start = list(k = 1, e = 2))
ggplot(mtcars,aes(wt,mpg)) +
geom_point() +
stat_fit_augment(method = "nls",method.args = args) +
stat_fit_tidy(method = "nls",method.args = args,label.x = "right",
label.y = "top",
aes(label = sprintf("\"y\"~`=`~%.3g %%*%% %.3g^{\"x\"}",
after_stat(k_estimate),
after_stat(e_estimate))),parse = TRUE )
❝第一种方法非常简单,但是通用性不强只适合数据量小的数据集进行分析,若使用数据较多则会进行报错提示,那么处理起来就比较棘手,下面介绍第二种方法分步进行「nls」分析。 ❞
nlsFit <- nls(formula=`mpg` ~ k*e^`wt`,
start = list(k=1,e=2),
data=mtcars,
control=nls.control(maxiter=200))
Nonlinear regression model
model: mpg ~ k * e^wt
data: mtcars
k e
49.6597 0.7456
residual sum-of-squares: 213.5
Number of iterations to convergence: 10
Achieved convergence tolerance: 2.043e-06
nlsParams <- nlsFit$m$getAllPars()
nlsEqn <- substitute(italic(y) == k %.% e^ italic(x),
list(k=format(nlsParams['k'],digits=3),
e=format(nlsParams["e"],digits=3)))
dlabel <- tibble(label="y = 49.7*0.746<sup>x</sup>",x=4,y=35)
ggplot(mtcars,aes(wt,mpg)) +
geom_point()+
stat_smooth(method = 'nls',
method.args = list(start = c(a=1, b=1)),
formula = y~a*exp(b*x), se = FALSE)+
geom_richtext(data=dlabel,aes(x=x,y=y,label=label),
fill=NA,label.color=NA,show.legend = F)+
theme_bw()