如何在R中执行折线回归分析?

时间:2018-08-26 07:06:01

标签: r

我有以下数据:

Treatment   Dose      Value
FeSo4       200       104.17
TQ1          6        98.17
TQ2          9        92
TQ3         12        86.67
TQ4         15        77.33
TQ5         18        71.33
TQ6         21        74.83
TQ7         24        82.17

如何在R中对此数据进行折线回归分析以得到如下图:

The image is included in following link

2 个答案:

答案 0 :(得分:1)

按R中的分段拟合线性模型的最佳方法是使用CRAN软件包segmented
接下来,我创建了一个新列,将列Treatment的列factor强制为其整数代码。

library(segmented)

df1$Num <- as.integer(df1$Treatment)

fit <- lm(Value ~ Num, df1)
summary(fit)

seg <- segmented(fit, seg.Z = ~Num, psi = 6)

plot(Value ~ Num, df1)    # plot the points
plot(seg, add = TRUE)     # plot the broken line
abline(v = seg$psi[2])    # plot the vertical at the breakpoint

数据。

df1 <- read.table(text = "
Treatment   Dose      Value
FeSo4       200       104.17
TQ1          6        98.17
TQ2          9        92
TQ3         12        86.67
TQ4         15        77.33
TQ5         18        71.33
TQ6         21        74.83
TQ7         24        82.17
", header = TRUE)

答案 1 :(得分:0)

另一种方法是首先找到阈值,然后拟合常规的lm()模型:

library(SiZer)
df <- read.table(text = "
Treatment   Dose      Value
FeSo4       200       104.17
TQ1          6        98.17
TQ2          9        92
TQ3         12        86.67
TQ4         15        77.33
TQ5         18        71.33
TQ6         21        74.83
TQ7         24        82.17
", header = TRUE)
df$Num <- as.integer(df$Treatment)

thr.pwl = piecewise.linear(df$Num, df$Value,
                             middle = 1, CI = FALSE, 
                             bootstrap.samples = 1000, sig.level = 0.001)
thr.pwl

[1] "Threshold alpha: 6.30159931424453" #This is the threshold you need
[1] ""
[1] "Model coefficients: Beta[0], Beta[1], Beta[2]" #The estimates here are the same as in model.pwl, however, with lm() you can include also other independent variables
(Intercept)           x           w 
  111.48333    -6.63000    13.97001

model.pwl <- lm(Value ~ Num*(Num >= 6.30) + Num*(Num < 6.30),
            data = df) 
summary(model.pwl)

您可以将其绘制为:

plot(thr.pwl)
abline(v = thr.pwl$change.point)

但是,使用piecewise.linear()只能使我们达到一个阈值,而使用segmented()可以使我们更多。