R: rollapplyr and lm factor error: Does rollapplyr change variable class?

。_饼干妹妹 提交于 2019-12-06 19:25:29

rollapply passes a matrix to the function so only pass the numeric columns. Using rolled from my prior answer and the setup in that question:

do.call("rbind", by(dat[c("x", "y")], dat[c("w", "z")], rolled))

Added

Another way to do it is to perform the rollapply over the row indexes instead of over the data frame itself. In this example we have also added the conditioning variables as extra output columns:

rolli <- function(ix) {
   data.frame(coef = rollapplyr(ix, width = 6, function(ix) { 
         coef(lm(y ~ x, data = dat, subset = ix))[2]
      }, by = 3), w = dat$w[ix][1], z = dat$z[ix][1])
}
do.call("rbind", by(1:nrow(dat), dat[c("w", "z")], rolli))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!