Search code examples
rlistdataframelapplyrollapply

rolling function to get coeff of regression from a list of dataframes


I want to get coefficient of regression for each data frame in a list of dataframes with a rolling period but somehow I am getting very different result from what I am looking for. I have tried the following code: my data looks like this

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)

I wish to get regression result for each element for rolling windows as a list ,which I can later bind

I am new to R. Any help would be much appreciated.


Solution

  • Providing a data.frame as the first rollapply argument will apply FUN to every column of the data.frame separately. Operating on data from two columns simultaneously can be achieved by moving a rolling window across the the sequence of row numbers in the 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