簡體   English   中英

為什么在rollapply窗口中將值轉換為字符串?

[英]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現在是字符? 以及如何修復它,以便在每個窗口中都能得到原始動物園對象的一部分?

根據對SO上其他帖子的一些了解,推出了自己的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
     ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM