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