更多新手问题......我试图理解为什么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现在是一个角色?以及如何修复它以便在每个窗口中获取原始动物园对象的切片?
根据对SO的其他posts的一些阅读,滚动我自己的rollapply功能。这只是将索引返回到数据(即zoo对象):
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
...
}