为什么在 rollapply window 中将值转换为字符串?

Why are values converted to strings in the rollapply window?

更多新手问题...我试图理解为什么 rollapply 将我所有的列都转换为字符串。假设我有这个:

> df <- data.frame(col1=c(1,2,3,4), 
                 col2=c("a","b","c","d"), 
                 col3=c("!","@","#","$"),
                 stringsAsFactors = F))
> v <- zoo(df, toupper(df$col2))
> v
  col1 col2 col3
A 1    a    !   
B 2    b    @   
C 3    c    #   
D 4    d    $  

然后我运行 rollapply:

> rollapply(v, 2, by.column = F, function(x) { 
+     sum(x[,"col1"])
+ })
 Error in sum(x[, "col1"]) : invalid 'type' (character) of argument 

为什么 col1 现在是一个角色?以及如何修复它,以便在每个 window?

中获得原始动物园对象的一部分

根据对 SO 上其他 posts 的一些阅读,滚动我自己的 rollapply 函数。这只是 returns 数据(即动物园对象)的索引:

rollapply.list <- function(data, width, FUN) {
  len <- NROW(data)
  add <- rep(0:(len-width),each=width)
  lst <- rep(1:(width),len-width+1)
  seq.list <- split(lst+add, add)
  lapply(seq.list, FUN)
}

然后将索引应用于原始数据,如:

rollapply.list(data=v, width=2, FUN=function(x) {
     slice <- v[x]   #slice out indexes from the original zoo object
     ...
}