2

我遇到了一个我无法理解的问题。这是注释代码:

library(zoo)
#Pattern p used as row feeding matrix to apply() for function f
> p
     [,1] [,2] [,3]
[1,]   -1    1    1
[2,]    1    1    1

#Function f supposed to take rows of matrix p as vectors,
#compare them with vector x and return index
f <- function(x) {  # identifies which row of `patterns` matches sign(x)
  which(apply(p,1,function(row)all(row==sign(x))))
}

#rollapplying f over c(1,-1,1,1) : there is no vector c(1,-1,1) in p
#so why the first atom is 1 ?
> rollapply(c(1,-1,1,1),width=3,f,align="left")
[1] 1 1

#rollapply identity, rollapply is supposed to feed row to the function right ?
> t = rollapply(c(1,-1,1,1),width=3,function(x)x,align="left")
     [,1] [,2] [,3]
[1,]    1   -1    1
[2,]   -1    1    1

#Feeding the first row of the precedent matrix to f is giving the expected result
> f(t[1,])
integer(0)

#rollapply feeds the rolls to the function
> rollapply(c(1,-1,1,1),width=3,function(x) paste(x,collapse=","),align="left")
[1] "1,-1,1" "-1,1,1"

#rollapply feeds vectors to the function
> rollapply(c(1,-1,1,1),width=3,function(x) is.vector(x),align="left")
[1] TRUE TRUE

#Unconsistent with the 2 precedent results
> f(c(1,-1,1))
integer(0)

基本上我不明白为什么当第一个滚动应该产生模式矩阵中不存在的向量时rollapply(c(1,-1,1,1),width=3,f,align="left")返回。相反,我期待结果。如果我将向量提供给我得到预期的结果,那么一定有一些我不明白但很奇怪的东西。在某些情况下,我有一个 mix但从来没有 mix或.1 1rollapply1 -1 1pNA 1rollapplyc(-1, -1, -1 ,-1)rollapplyNA NA1 2NA 1NA 2

4

2 回答 2

3

根据 G. Grothendieck,rollapply 不支持产生零长度输出的函数。f可以通过在返回特定输出的函数中添加条件来解决该问题,以防它返回零长度输出。

  f <- function(x) {  # identifies which row of `patterns` matches sign(x)
    t <- which(apply(patterns,1,function(row)all(row==sign(x))))
    ifelse(length(t)==0, return(0), return(t))
  }
于 2014-10-06T12:37:27.937 回答
0

为了完整起见,引用 GGrothendieck 的评论。“rollapply 不支持产生零长度输出的函数。”这与下面的行为一致。

进一步的混乱,至少对我来说(这应该是一个评论,但我想要一些体面的格式):

sfoo<-c(1,-1,1,1,1,-1,1,1) rollapply(sfoo,width=3,function(j){k<-f(j);print(j);return(k)}) [1] 1 -1 1 [1] -1 1 1 [1] 1 1 1 [1] 1 1 -1 [1] 1 -1 1 [1] -1 1 1 [1] 1 2 1 1 2 1

然后我尝试了:

ff<-function(x) which(rowSums(p)==sum(x))
sbar<-c(0,1,1,1,-1,0,-1)
rollapply(sbar,width=3,function(j){k<-ff(j);print(j);return(k)})
[1] 0 1 1
[1] 1 1 1
[1]  1  1 -1
[1]  1 -1  0
[1] -1  0 -1
[1] 2 1 2 1 2

看起来确实像是rollapply在进行一种na.locf填充操作。

于 2014-10-06T12:16:57.130 回答