优化代码以计算R中生成的每个模型的coef和r平方

时间:2019-04-21 17:46:11

标签: r regression

基于 this stackoverflow topic,我想提取系数。

从“钻石”数据集中,我使用nest()函数针对两个分类变量(颜色和切工)拆分钻石数据集。然后为每个模型计算系数和r_square并将它们存储为数据帧。

我通过以下代码成功做到了:

df_dia <- diamonds %>%
  group_by(color, cut) %>% nest() %>% 

  # generate summary
  mutate(fit = map(data, ~lm(price ~ carat, data=.)), summary= map(fit, glance)) %>%
  unnest(summary) %>%

  # generate coef
  mutate(fit = map(data, ~lm(price ~ carat, data=.) %>%coef %>% 
                                        as.list %>% as_tibble)) %>%
  unnest(fit) %>% unnest(data) %>%
  select(color, cut, `(Intercept)`, carat, r.squared)

但是,它效率不高,因为它必须进行两次回归。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

为什么不使用sapply:

fa = split(diamonds,f = list(diamonds$color,diamonds$cut) )
df_d=data.frame(t(sapply(fa,function(dft){  ## dft=fa[[1]]
  m1=lm(price ~ carat,dft)
  c(coef(m1),r.squared=summary(m1)$r.squared)
  })))
df_dn=do.call("rbind",strsplit(row.names(df_d),".",fixed = T))
df_d = cbind(df_dn,df_d)
colnames(df_d)[1:2]= c("color", "cut")
head(df_d)

# head(df_d)
#        color  cut  X.Intercept.  carat r.squared
# D.Fair     D Fair    -2255.690 7115.086 0.7705523
# E.Fair     E Fair    -2612.316 7348.326 0.8100614
# F.Fair     F Fair    -2214.511 6677.834 0.7531280
# G.Fair     G Fair    -2199.924 6289.356 0.7370402
# H.Fair     H Fair    -2297.343 6096.767 0.7396489
# I.Fair     I Fair    -3097.742 6496.508 0.8263858