本文介绍了为什么在 rollapply 窗口中将值转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

More newbie questions... I am trying to understand why rollapply is turning all my columns to strings. Suppose I have this:

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

And then I run rollapply:

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

为什么 col1 现在是一个字符?以及如何修复它以便在每个窗口中获得原始动物园对象的一部分?

Why is col1 now a character? and how do I fix it so I get a slice of my original zoo object in each window?

推荐答案

基于对其他帖子 关于 SO.这只是将索引返回到数据中(即动物园对象):

Rolled my own rollapply function based on some reading of other posts on SO. This just returns the indexes into the data (i.e. the zoo object):

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

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

and then apply the indexes to the original data like:

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

这篇关于为什么在 rollapply 窗口中将值转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 22:25