使用带有 dplyr 包的数据框执行分段线性回归时如何使用分段包?

How to use segmented package when working with data frames with dplyr package to perform piecewise linear regression?

我的数据框是按组分隔的。我想对每个组执行分段线性回归,为此我打算使用 segmented 包。

首先,我使用 dplyr 包为每个组创建了线性模型。下一步是对这些模型进行细分,但这是我遇到的问题。任何提示或其他方式来做到这一点?最终目的是利用这些线段做一个图。

library(dplyr)
library(segmented)

Group <- c("A", "B")
x <- 0:10
y <- c(0, 0.4, 0.6, 0.8, 0.9, 0.9, 0.95, 0.97, 0.98, 0.99, 1,
       0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1)

df <- expand.grid(x = x,
                  Group = Group)

df$y <- y

Segment <- df %>%
  group_by(Group) %>%
  do(my.lm = lm(data = .,
                formula = y ~ x))

不成功的尝试:

Segment <- df %>%
  group_by(Group) %>%
  do(my.lm = lm(data = .,
                formula = y ~ x),
     my.seg = segmented(my.lm,
                        seg.Z = x))


Segment <- df %>%
  group_by(Group) %>%
  do(my.lm = lm(data = .,
                formula = y ~ x)) %>%
  do(my.seg = segmented(my.lm,
                        seg.Z = x))


Segment <- df %>%
  group_by(Group) %>%
  do(my.lm = lm(data = .,
                formula = y ~ x)) %>%
  mutate(my.seg = segmented(my.lm,
                        seg.Z = x))

一个选项是用 tryCatch 和 return 包装一个 NA 以表示可能的错误

library(dplyr)
out <- df %>% 
    nest_by(Group) %>%
    mutate(my.lm = list(lm(y ~ x, data = data)),
        my.seg = list(tryCatch(segmented(my.lm, seg.Z = ~ x),
         error = function(e) list(NA))))

-输出

> out
# A tibble: 2 x 4
# Rowwise:  Group
  Group               data my.lm  my.seg    
  <fct> <list<tibble[,2]>> <list> <list>    
1 A               [11 × 2] <lm>   <segmentd>
2 B               [11 × 2] <lm>   <list [1]>
> out$my.seg
[[1]]
Call: segmented.lm(obj = my.lm, seg.Z = ~x)

Meaningful coefficients of the linear terms:
(Intercept)            x         U1.x  
    0.03333      0.30000     -0.27488  

Estimated Break-Point(s):
psi1.x  
 2.691  

[[2]]
[[2]][[1]]
[1] NA