如何使用分段包提取斜率和截取变量并使用r放入数据帧?

时间:2018-01-23 18:40:42

标签: r piecewise

有没有人可以告诉我如何获得分段包装产生的斜坡和拦截并放置在数据框中?这将最终用于将斜率和截距排列回其原始值。请参阅下面的数据(我从另一篇文章中获取)。

#load包     库(分段)     库(tidyverse)

#set seed and develop data
set.seed(1)
Y<-c(13,21,12,11,16,9,7,5,8,8)
X<-c(74,81,80,79,89,96,69,88,53,72)
age<-c(50.45194,54.89382,46.52569,44.84934,53.25541,60.16029,50.33870,
   51.44643,38.20279,59.76469)
dat=data.frame(Y=Y,off.set.term=log(X),age=age)

#run initial GLM
glm.fit=glm(Y~age+off.set.term,data=dat,family=poisson)
summary(glm.fit)

#run segmented glm
glm.fitted.segmented <- segmented(glm.fit, seg.Z=~age + off.set.term, psi = 
list(age = c(50,53), off.set.term = c(4.369448)))

#Get summary, slopes and intercepts
summary(glm.fitted.segmented)
slope(glm.fitted.segmented)
intercept(glm.fitted.segmented)

1 个答案:

答案 0 :(得分:1)

library(broom)
library(dplyr)
library(tidyr)
library(stringr)

slopes <-
  bind_rows(lapply(slope(glm.fitted.segmented), tidy), .id = "variable") %>%
  mutate(type = str_extract(.rownames, "^[a-z]+"),
         model = str_extract(.rownames, "[0-9]+$")) %>%
  select(variable, model, type, estimate = "Est.")
intercepts <-
  bind_rows(lapply(intercept(glm.fitted.segmented), tidy), .id = "variable") %>%
  mutate(type = str_extract(.rownames, "^[a-z]+"),
         model = str_extract(.rownames, "[0-9]+$")) %>%
  select(variable, model, type, estimate = "Est.")

bind_rows(slopes, intercepts) %>%
  spread(type, estimate)

使用tidy函数,您可以轻松地为每个变量提取data.frame,然后提取模型和单位类型。将它们绑定在一起并将类型和估计值扩展到以变量,模型,截距和斜率结束。