【问题标题】:How can I run a regression daily and save the coefficients in a new dataset?如何每天运行回归并将系数保存在新数据集中?
【发布时间】:2019-06-12 19:14:26
【问题描述】:

我有一个数据集,其中包含从 1975 年到 2018 年每个国家(总共 16 个国家)每个行业(总共 10 个行业)的每日收益率。现在我需要每天和每周运行横截面回归并保存单独数据集中的系数。

我尝试了以下代码。但是每天的估算值都是一样的。

fitted_models = Data %>% 
                group_by(Data$Date) %>% 
                do(model = lm(Data$RoR ~ Data$Country + Data$Industry, data=Data))

fitted_models$model

我需要包括以下对比:

contrasts(All0$Country) <- contr.sum(16, contrasts=TRUE)
contrasts(All0$Industry) <- contr.sum(10, contrasts=TRUE)

然后我收到以下错误消息

Error in contrasts&lt;-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels In addition: Warning messages: 1: contrasts dropped from factor Country due to missing levels 2: contrasts dropped from factor Industry due to missing levels

这是我的数据样本。随着时间的推移,RoR 会出现价值。

   Country        Date       Industry     RoR
   <chr>          <date>     <chr>      <dbl>
 1 Finland        1975-01-01 Basic Mats    NA
 2 Austria        1975-01-01 Basic Mats    NA
 3 Spain          1975-01-01 Basic Mats    NA
 4 United Kingdom 1975-01-01 Basic Mats    NA
 5 Norway         1975-01-01 Basic Mats    NA
 6 Germany        1975-01-01 Basic Mats    NA
 7 France         1975-01-01 Basic Mats    NA
 8 Italy          1975-01-01 Basic Mats    NA
 9 Portugal       1975-01-01 Basic Mats    NA
10 Switzerland    1975-01-01 Basic Mats    NA 

【问题讨论】:

  • 将它们导出到文件中? stackoverflow.com/questions/49958828/…
  • 我需要它们在环境中进行进一步分析。主要问题是每天运行回归。但是谢谢你,否则我将再次导出和导入。
  • 放弃Data$ 可能是朝着正确方向迈出的一步。另一种方法是使用日期和其他所有变量之间的交互来运行单个回归。
  • 但是如果我只运行一次回归,我如何从中获得系数的时间序列?
  • 我过去曾使用apply 对数据行进行回归。也许调查一下?

标签: r save regression


【解决方案1】:

使用data.table 包进行分组操作可能是解决这个问题的好方法——我使用mtcars 作为示例数据集,因为您没有提供数据集,但该方法会与您的数据相同。在这里,我使用cyl 作为分组列,但在您的情况下,它将是Date

library(data.table)

DT <- as.data.table(mtcars)

DT[,as.list(lm(mpg ~ wt+qsec)$coefficients), by = .(cyl)]

#    cyl (Intercept)        wt      qsec
# 1:   6    25.46173 -5.201906 0.5838640
# 2:   4    24.88427 -7.513576 0.9903892
# 3:   8    14.02093 -2.813754 0.7352592

【讨论】:

  • 谢谢!我需要包括以下对比:contrasts(All0$Country) &lt;- contr.sum(16, contrasts=TRUE) contrasts(All0$Industry) &lt;- contr.sum(10, contrasts=TRUE) 但我收到以下错误消息然后Error in contrasts(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels In addition: Warning messages: 1: contrasts dropped from factor Country due to missing levels 2: contrasts dropped from factor Industry due to missing levels
  • 嗯。我怀疑这是可能的,但是如果您正在使用的数据集没有一些明确性,就很难进一步提供帮助。您能否在问题中提供DataAll0 data.frames 的子集? (See Here for some guidelines and instructions ) 另外,请将此评论中的附加问题添加到您的原始问题中。
  • 希望这对我的问题有更多帮助。感谢您的努力。
猜你喜欢
  • 1970-01-01
  • 2012-01-20
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
相关资源
最近更新 更多