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

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

这个问题建立在上一个问题的基础上,我在这里得到了很好的回答。

您不知道当扩展到实际数据而不是示例数据时,代码无法正常工作吗?

我有一个比较大的数据集,具有以下特征。

str(T0_satData_reduced)
'data.frame':   45537 obs. of  5 variables:
 $ date   : POSIXct, format: "2014-11-17 08:47:35" "2014-11-17 08:47:36" "2014-11-17 08:47:37" ...
 $ trial  : Factor w/ 5 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ vial   : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 1 ...
 $ O2sat  : num  95.1 95.1 95.1 95.1 95 95.1 95.1 95.2 95.1 95 ...
 $ elapsed: num  20 20 20.1 20.1 20.1 ...

上一个问题涉及将 O2sat 的滚动回归作为 elapsed 的函数应用的愿望,但按因素 trial 和 [=17= 对回归进行分组].

以下代码摘自我上一个问题的答案(针对完整数据集而不是练习数据集进行了简单修改)

rolled <- function(df) {
   rollapplyr(df, width = 600, function(m) { 
   coef(lm(formula = O2sat ~ elapsed, data = as.data.frame(m)))
   }, by = 60, by.column = FALSE)
 }

T0_slopes <- ddply(T0_satData_reduced, .(trial,vial), function(d) rolled(d))

但是,当我 运行 这段代码时,我收到了一系列错误或警告(这里是前两个)。

Warning messages:
1: In model.response(mf, "numeric") :
using type = "numeric" with a factor response will be ignored
2: In Ops.factor(y, z$residuals) : - not meaningful for factors

我不确定这个错误是从哪里来的,因为我已经证明 elapsedO2sat 都是数字,所以我没有回归因素。但是,如果我像这样在上面的 rolled 函数中强制它们都是数字。

...
coef(lm(formula = as.numeric(O2sat) ~ as.numeric(elapsed), data = as.data.frame(m)))
...

我不再收到错误,但是,我不知道为什么这会解决错误。此外,由此产生的回归看起来很可疑,因为截距项似乎小得不合适。

关于为什么我会收到这些错误以及为什么使用 as.numeric 似乎可以消除错误(如果可能仍然提供不适当的回归项)有什么想法吗?

谢谢

rollapply 将矩阵传递给函数,因此只传递数字列。使用我之前的回答中的 rolled 和该问题中的设置:

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

已添加

另一种方法是对行索引而不是数据框本身执行滚动应用。在此示例中,我们还添加了条件变量作为额外的输出列:

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))