我遇到了一个我无法理解的问题。这是注释代码:
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 1
rollapply
1 -1 1
p
NA 1
rollapply
c(-1, -1, -1 ,-1)
rollapply
NA NA
1 2
NA 1
NA 2