拟合一系列线性模型,为不同的分组变量分离因变量

时间:2016-03-19 18:47:26

标签: r dplyr broom

嗨:我有三个连续因变量和一个三个变量的自变量。我想看看每个国家的y1到y6~x1的系数是多少。有没有办法用dplyr和扫帚整齐地做到这一点?我知道dplyr相当不错,但我是扫帚的新手。

#one random independent variable 
x1<-rnorm(100, mean=5, sd=1)
#one random dependent variable
y1<-rnorm(100, mean=2, sd=2)
#two random dependent variables, in reality I have six
y2<-rnorm(100, mean=3, sd=1)
#Grouping variable. 
country<-sample(seq(1,3,1), size=100, replace=T)
#data frame
df<-data.frame(x1, y1, y2, country)
#I would like to see what the coefficients are for y1~x1 
and then y2 ~x2 for   country 1, country 2, country 3, etc. 
library(dplyr)
#Fit one model for each of three countries
test<-df%>%
 group_by(country) %>%
  do(mod.y1=lm(y1~x1, data=.))
#print results
test$mod.y1

1 个答案:

答案 0 :(得分:0)

您可以使用来自tidyr的gather和来自扫帚的tidy的组合。首先,不是为每个国家/地区做一个适合,而是为y1 / y2和国家/地区的每个组合做一个适合:

library(tidyr)
library(broom)

fits <- df %>%
  gather(variable, value, y1, y2) %>%
  group_by(country, variable) %>%
  do(mod = lm(value ~ x1, .))

然后你可以整理它们(使用扫帚)并过滤掉拦截术语:

td <- tidy(fits, mod) %>%
  filter(term != "(Intecept)")

这为您提供了一个如下所示的数据框td

Source: local data frame [6 x 7]
Groups: country, variable [6]

  country variable  term     estimate std.error   statistic   p.value
    (dbl)    (chr) (chr)        (dbl)     (dbl)       (dbl)     (dbl)
1       1       y1    x1  0.106140467 0.3835857  0.27670599 0.7835458
2       1       y2    x1 -0.004725751 0.1837192 -0.02572268 0.9796168
3       2       y1    x1 -0.193700062 0.4690913 -0.41292614 0.6826979
4       2       y2    x1  0.094083592 0.2024151  0.46480518 0.6455421
5       3       y1    x1 -0.223523980 0.3820297 -0.58509584 0.5631692
6       3       y2    x1 -0.029720338 0.2116219 -0.14044074 0.8893172

您的estimate列是估算系数。