遍历变量以进行回归

时间:2018-12-22 16:08:31

标签: r loops statistics regression linear-regression

我想知道是否可以在此数据帧上运行多个回归:

 Country Years FDI_InFlow_MilUSD FDI_InFlow_percGDP FDI_InStock_MilUSD FDI_OutFlow_MilUSD FDI_OutFlow_percGDP
    1 Netherlands  1990          11063.31               3.52           71827.79           14371.94               34.96
    2     Romania  1990              0.01               0.00               0.01              18.00                0.16
    3 Netherlands  1991           6074.61               1.88           75404.38           13484.54               37.09
    4     Romania  1991             40.00               0.13              44.00               3.00                0.29
    5 Netherlands  1992           6392.10               1.78           73918.54           13153.78               33.15
    6     Romania  1992             77.00               0.37             122.00               4.00                0.38

在这种情况下,我想对所有感兴趣的变量3:7进行回归(我的原始数据有10个变量,但我认为这足以理解我想要的意思)。另外,我想将lm结果存储在数据框中,并按国家/地区分组(如果可能的话),而不是为每个国家/地区制作2个df,然后循环遍历它们。.

这是一个通缉的df的例子(此人未分组):

#          term   estimate   std.error  statistic      p.value
# 1  (Intercept) -3.2002150 0.256885790 -12.457735 8.141394e-25
# 2 Sepal.Length  0.7529176 0.043530170  17.296454 2.325498e-37
# 3  (Intercept)  3.1568723 0.413081984   7.642242 2.474053e-12
# 4  Sepal.Width -0.6402766 0.133768277  -4.786461 4.073229e-06
# 5  (Intercept) -0.3630755 0.039761990  -9.131221 4.699798e-16
# 6 Petal.Length  0.4157554 0.009582436  43.387237 4.675004e-86

这里是预期结果的示例:在这种情况下,计算是针对两个国家/地区的,每个国家/地区只分配了两次

   Country         term     estimate    std.error statistic      p.value
1 Netherlands  (Intercept) -67825.16741 2.229068e+04 -3.042759 3.615586e-03
2 Netherlands GDP_pcap_USD     14.04734 7.908839e-01 17.761576 3.285528e-24
3     Romania  (Intercept) -67825.16741 2.229068e+04 -3.042759 3.615586e-03
4     Romania GDP_pcap_USD     14.04734 7.908839e-01 17.761576 3.285528e-24

我使用了以下代码行:FDI2 %>% group_by(Country) %>% do(tidy(lm(FDI_InStock_MilUSD ~ GDP_pcap_USD, data= FDI2)))

1 个答案:

答案 0 :(得分:0)

如果我的理解正确,以下将满足您的要求。所有需要注意的是,lm可以适合多元回归模型并返回类"mlm"的对象。

models <- lm(as.matrix(df1[-(1:2)]) ~ Country + Years, df1)

class(models)
#[1] "mlm" "lm"


smry <- summary(models)
result <- lapply(smry, coef)
result <- do.call(rbind, result)

head(result)
                    Estimate   Std. Error    t value   Pr(>|t|)
#(Intercept)     2.294616e+06 1.847179e+06  1.2422273 0.30241037
#CountryRomania -7.804337e+03 1.515033e+03 -5.1512655 0.01418200
#Years          -1.148555e+03 9.277644e+02 -1.2379813 0.30377452
#(Intercept)     6.843108e+02 7.063395e+02  0.9688129 0.40410011
#CountryRomania -2.226667e+00 5.793307e-01 -3.8435157 0.03107572
#Years          -3.425000e-01 3.547662e-01 -0.9654247 0.40554755
相关问题