滚动函数以从数据框列表中获取回归系数

时间:2018-08-17 09:18:06

标签: r list dataframe lapply rollapply

我想获取具有滚动周期的数据帧列表中每个数据帧的回归系数,但不知何故,我得到的结果与所寻找的结果截然不同。 我尝试了以下代码: 我的数据看起来像这样

library("zoo") ## for rollapply()
data <- list(mtcars,mtcars,mtcars)

fapplyFunction <- function(x){
coef(lm(mpg ~ drat, data=as.data.frame(x)))}

coef_list <- lapply(data, rollapply, 20, fapplyFunction, partial = FALSE, by.column = FALSE)

我希望获得滚动窗口的每个元素的回归结果作为列表,以后可以绑定

我是R的新手。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

data.frame作为第一个rollapply参数,将FUN分别应用于data.frame 的每一列。通过在data.frame中的行号序列上移动滚动窗口,可以同时处理来自两列的数据

lapply(data, function(x)
    rollapply(1:nrow(x), 20, function(i) coef(lm(mpg ~ drat, data = x[i, ]))))
#[[1]]
#      (Intercept)     drat
# [1,]   -11.70889 8.981350
# [2,]   -12.09923 9.124252
# [3,]   -11.47530 9.015324
# [4,]   -11.91551 9.124458
# [5,]   -12.51405 9.094820
# [6,]   -12.10843 8.994363
# [7,]   -15.57941 9.937651
# [8,]   -14.06719 9.511583
# [9,]   -14.42693 9.684131
#[10,]   -11.68393 8.789089
#[11,]   -12.12158 8.954089
#[12,]   -13.12850 9.243443
#[13,]   -12.81957 9.095040
# 
#[[2]]
#      (Intercept)     drat
# [1,]   -11.70889 8.981350
# [2,]   -12.09923 9.124252
# [3,]   -11.47530 9.015324
# [4,]   -11.91551 9.124458
# [5,]   -12.51405 9.094820
# [6,]   -12.10843 8.994363
# [7,]   -15.57941 9.937651
# [8,]   -14.06719 9.511583
# [9,]   -14.42693 9.684131
#[10,]   -11.68393 8.789089
#[11,]   -12.12158 8.954089
#[12,]   -13.12850 9.243443
#[13,]   -12.81957 9.095040
# 
#[[3]]
#      (Intercept)     drat
# [1,]   -11.70889 8.981350
# [2,]   -12.09923 9.124252
# [3,]   -11.47530 9.015324
# [4,]   -11.91551 9.124458
# [5,]   -12.51405 9.094820
# [6,]   -12.10843 8.994363
# [7,]   -15.57941 9.937651
# [8,]   -14.06719 9.511583
# [9,]   -14.42693 9.684131
#[10,]   -11.68393 8.789089
#[11,]   -12.12158 8.954089
#[12,]   -13.12850 9.243443
#[13,]   -12.81957 9.095040