【R语言数据分析二:回归拟合模型】

2021.4.29
持续更新中。。。

参考:《R数据可视化手册》、学术数据分析及可视化


    需要提前安装的包:tidyverseaomiscdrcbroom。大部分可以通过install.packages()函数直接安装。aomisc通过一下命令安装
    回归拟合主要用作构建简单回归模型以及可视化拟合线。

install.packages('remotes')
remotes::install_github("OnofriAndreaPG/aomisc")

1. 线性拟合模型

1.1 简单线性拟合模型

形如:y = a +b*x

x <- seq(5,50,5)
y <- c(12.6, 74.1, 157.6, 225.5, 303.4, 462.8, 669.9, 805,3, 964,2, 1169)
plot(x, y)
fit <- lm(Y ~ X)
#查看拟合的参数信息
summary(fit)
#画图
plot(X, Y)
abline(fit)
  1. 对于线性模型来说可能会通过一些P值或R平方来评估模型的好坏,但是在非线性模型中并不适用。
  2. 评估线性模型的好坏,看R平方(越大越好),和残差(越小越好),但是拟合后的模型应该越简单越好。

1.2 广义线性拟合(高阶)

形如:y = a +b*x +c*x^2y = a +b*x + c*x^2 + d*x^3等(一般不超过三次方)

x <- seq(5,50,5)
y <- c(12.6, 74.1, 157.6, 225.5, 303.4, 462.8, 669.9, 805.3, 964.2, 1169)

#两种二项式拟合方式
fit1 <- lm(Y ~ X + I(X^2))
model1 <- nls(Y ~ NLS.poly2(X,a,b,c))
#三项式拟合
fit2 <- lm(Y ~ X + I(X^2) +I(X^3))

#利用lines()函数拟合后绘图
plot(X, Y)
lines(X, predict(model), col = 'green')
lines(X, predict(fit2), col = 'red')
  1. 一般来说多项式y = a +b*x +c*x^2等和y = a + b*x都称为线性模型。
  2. predict()函数会根据X的值计算Y的值。

1.3 利用ggplot进行绘图

ggplot(mpg, aes(displ,hwy))+
  geom_point()+
  #简单线性回归
  geom_smooth(method = 'lm', formula = 'y ~ x', 
              se = F, color = 'green')+
  #二次项线性回归
  geom_smooth(method = 'lm', formula = 'y ~ poly(x, 2)', 
              se = F, color = 'red')+
  #三次项线性回归
  geom_smooth(method = 'lm', formula = 'y ~ splines::bs(x, 3)', 
              se = F, color = 'yellow')+
  geom_smooth(se = F)

2. 非线性回归

2.1 幂函数拟合

形如:y = a*x^b

幂函数

data(speciesArea)
#可用两种方法建立模型
model6 <- nls(numSpecies ~ NLS.powerCurve(Area, a, b), data = speciesArea)
model7 <- drm(numSpecies ~ Area, fct = DRC.powerCurve(), data = speciesArea)
#整合数据
df <- tibble(V1 = seq(1, 256, 1), 
             V2 = predict(model6, newdata = data.frame(Area = seq(1, 256, 1))))
#利用ggplot()绘图
ggplot(speciesArea, aes(Area, numSpecies))+
  geom_point()+
  geom_line(data = df, aes(V1, V2), color = 'red')

2.2 对数函数拟合

形如:y = a + b*log(x)

对数函数

X <- c(1, 2, 4, 5, 7, 12)
Y <- c(1.97, 2.32, 2.67, 2.71, 2.86, 3.09)
df <- tibble(X, Y)
#可用三种方法构建模型
model8 <- lm(Y ~ log(X))
model9 <- nls(Y ~ NLS.logCurve(X, a, b))
model10 <- drm(Y ~ X, fct = DRC.logCurve())
#整合数据
df1 <- tibble(V1 = seq(1,12,0.1),
              V2 = predict(model8, newdata = data.frame(X = seq(1,12,0.1))))
#绘图
ggplot(df, aes(x = X, y = Y))+
  geom_point()+
  geom_line(data = df1, aes(V1, V2), color ='red')

predict()函数参数:
    1. Model:构建的模型。(就是数学表达式)
    2. newdata:要以数据框的形式带入,同时数据框中的变量名要与原模型里的一致。

你可能感兴趣的:(【R语言数据分析二:回归拟合模型】)