0

嗨:我有六个连续因变量和三个国家/地区的一个自变量。我想看看每个国家的 y1 到 y6 ~ x1 的系数是多少。有没有办法用 dplyr 和 broom 巧妙地做到这一点?我对 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
4

1 回答 1

0

您可以使用gatherfrom tidyr 和tidyfrom broom 的组合。首先,不是为每个国家做一个适合,而是为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列是估计系数。

于 2016-03-21T01:54:52.183 回答